LINQ选择与列表不同吗? [英] LINQ Select distinct from a List?
本文介绍了LINQ选择与列表不同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下列表:
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"));
如何检索与城市名称不同的人员列表?
How do I retrieve a list of persons differing from the city name?
预期结果:
与城市名称不同的列表(人员)的数组/集合:
An Array/Collection of lists (persons) differing from the city name:
result[0] = List<Person> where city name = "1"
result[1] = List<Person> where city name = "2"
result[n] = List<Person> where city name = "whatever"
推荐答案
您可以使用LINQ按城市对人员列表进行分组:
You could use LINQ to group the persons list by city:
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);
}
}
这篇关于LINQ选择与列表不同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文