LINQ Select与List不同?
我有以下列表:
class Person { public String Name { get; set; } public String LastName { get; set; } public String City { get; set; } public Person(String name, String lastName, String city) { Name = name; LastName = lastName; City = city; } } ... personList.Add(new Person("a", "b", "1")); personList.Add(new Person("c", "d", "1")); personList.Add(new Person("e", "f", "2")); personList.Add(new Person("g", "h", "1")); personList.Add(new Person("i", "j", "2")); personList.Add(new Person("k", "l", "1"));
如何检索与城市名称不同的人员列表?
期待结果:
不同于城市名称的数组/列表(人员)集合:
result[0] = List where city name = "1" result[1] = List where city name = "2" result[n] = List where city name = "whatever"
您可以使用LINQ按城市对人员列表进行分组:
var groupedPersons = personList.GroupBy(x => x.City); foreach (var g in groupedPersons) { string city = g.Key; Console.WriteLine(city); foreach (var person in g) { Console.WriteLine("{0} {1}", person.Name, person.LastName); } }
除了Darin Dimitrov的答案之外,查询语法中的相同内容如下:
var groupByCityQuery = from person in personList group person by person.City into grouping select grouping;
从这个评论判断:不,我不是一个列表,其中包含所有包含1作为城市的人和另一个包含2作为城市的人…
我们可以这样做:
var city1People = personList.Where(x => x.city == "1").ToList(); var city2People = personList.Where(x => x.city == "2").ToList();
如果这是一个更有活力的东西,就像你将有N个城市并想要每个城市的个人列表一样,你将需要返回一组列表。