C# 使用 linq 选择与我的条件匹配的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17722670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:18:20  来源:igfitidea点击:

select object which matches with my condition using linq

c#.netlinq

提问by panjo

I have list of type Person which has 3 properties Id, Name, Age

我有一个 Person 类型列表,它有 3 个属性 Id、Name、Age

var per1 = new Person((1, "John", 33);
var per2 = new Person((2, "Anna", 23);

var persons = new List<Person>();
persons.Add(per1);
persons.Add(per2);

using linq I want to select person which age matched with my input, for example 33.

使用 linq 我想选择年龄与我的输入相匹配的人,例如 33。

I know how to use any but I dont know how to select object which matches with my condition.

我知道如何使用 any 但我不知道如何选择符合我的条件的对象。

采纳答案by ChaseMedallion

For one match:

对于一场比赛:

var match = persons.Single(p => your condition);

For many matches, use persons.Where(condition). There are also many variants of picking just one person, such as FirstOrDefault, First, Last, LastOrDefault, and SingleOrDefault. Each has slightly different semantics depending on what exactly you want.

对于许多匹配项,请使用persons.Where(condition). 仅选择一个人也有多种变体,例如 FirstOrDefault、First、Last、LastOrDefault 和 SingleOrDefault。每个都有略微不同的语义,具体取决于您到底想要什么。

回答by Adil

You can use Enumerable.Whereand it will return all the matching elements collection.

您可以使用Enumerable.Where,它将返回所有匹配的元素集合。

var res = persons.Where(c=>c.AttributeName == 23);

If you want to ensure you have only match you can use single.

如果你想确保你只有匹配,你可以使用单个。

var res = persons.Single(c=>c.AttributeName == 23);

SingleReturns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.

Single返回序列中的唯一元素,如果序列中不完全是一个元素,则抛出异常。

回答by Murugavel

It is very simple.

这很简单。

var per1 = new Person(1, "John", 33);
var per2 = new Person(2, "Anna", 23);
var persons = new List<Person>();
persons.Add(per1);
persons.Add(per2);
var sirec = persons.Select(x => x.age = 33);

Try this and let me know

试试这个,让我知道

Note: If it is single value use "Single" instead of "Select"

注意:如果是单值,请使用“Single”而不是“Select”