2010-03-31 43 views
5

foreach(var person in peopleList.Where(person => person.FirstName ==“Messi”)) { selectPeople.Add(person); }用LINQ隐藏 - 基本选择

我只是想知道是否有任何方法来简化这个使用LINQ。

像,而不是考虑所有我试图使用LINQ只需填写清单的“梅西”的人...试图像...

var selectPeople = peopleList.Select(x=>x.FirstName=="Messi");

然后我可以在没有检查的情况下添加列表中的每个人。但它没有按计划运作。

也许没有必要简化表达式。但这个问题似乎值得加强我的LINQ知识。

+0

我现在已经得到了'VAR selectPeople = peopleList.Where(人=> person.Name == “梅西”)ToList() ;'所以我想这个问题真的是关于如何使用Select和SelectMany – baron 2010-03-31 00:55:30

+1

'SelectMany'用于每个项目可以返回多个结果并且想要将它们组合成单个结果集。例如。 'IEnumerable allChildren = person.SelectMany(person => person.GetChildren());'你不需要用你的例子。 – 2010-03-31 01:05:24

+1

此外,当您使用lambdas扩展方法而不是查询表达式时,“Select”常常是多余的。但是如果你想将对象投影到别的东西上,使用'Select'。例如,当FirstName等于“Messi”时,如果你只想要一个LastNames列表,你可以像'peopleList.Where(p => p.FirstName ==“Messi”)那样做。Select(p => p.LastName) ;',这应该导致一个'IEnumerable '代表符合给定条件的所有人的姓氏。 – 2010-03-31 01:08:27

回答

5

你很近。在不知情的情况下实际完成。

var selectPeople = peopleList.Where(x=>x.FirstName == "Messi"); 

这将创建一个IEnumerable<X>,其中X是人类列表中的任何类型。

查询表达式语法将

var selectPeople = from person in peopleList 
        where person.FirstName == "Messi" 
        select person; 

,并使之在混凝土中列表格式,我相信你也已经发现了.ToList()扩展。

1

peopleList是什么类型?我相信它必须是LINQ工作的一种IEnumerable类型。

var selectPeople = peopleList.AsEnumerable().Select(x=>x.FirstName=="Messi"); 

既然是列表,并钉在你的选择上List<X>呼叫类型AsEnumerable(),它应该工作。

+0

它是'列表' – baron 2010-03-31 00:58:56

+0

尝试上面的行,看看是否有效,我们在这里铸造为Enumerable .... – Gabe 2010-03-31 00:59:34

+1

'AsEnumerable()'是不必要的。另外'Select'将导致'IEnumerable '不是'IEnumerable ' – 2010-03-31 01:14:20

1
var selectPeople = new List<Person>(peopleList.Where(x=>x.FirstName=="Messi")); 

,或者如果你已经有了一个名单:

selectPeople.AddRange(peopleList.Where(x=>x.FirstName=="Messi"));