gpt4 book ai didi

c# - LINQ Select 与 List 不同?

转载 作者:太空狗 更新时间:2023-10-29 20:59:34 24 4
gpt4 key购买 nike

我有以下列表:


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?

Expecting Results:

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 按城市对人员列表进行分组:

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);
}
}

关于c# - LINQ Select 与 List 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7572006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com