LINQ选择与列表不同的选项
本文关键字:选项 列表 选择 LINQ | 更新日期: 2023-09-27 18:09:55
我有以下列表:
<>之前
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);
}
}
除了Darin Dimitrov的回答,下面是相同的查询语法:
var groupByCityQuery = from person in personList
group person by person.City into grouping
select grouping;
根据这个评论判断:不,我不想要一个包含所有person的列表,其中包含1作为一个城市,另一个包含2作为一个城市…
我们可以这样做:
var city1People = personList.Where(x => x.city == "1").ToList();
var city2People = personList.Where(x => x.city == "2").ToList();
如果这是更动态的东西,比如你将有N个城市,并想要每个城市的个人列表,你将需要返回列表的集合