c# – LINQ选择与列表不同?
发布时间:2020-12-15 17:45:49 所属栏目:百科 来源:网络整理
导读:我有以下列表: 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; }
我有以下列表:
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<Person> where city name = "1" result[1] = List<Person> where city name = "2" result[n] = List<Person> 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); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |