微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 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"));

如何检索与城市名称不同的人员列表?

期待结果:

不同于城市名称的数组/列表(人员)集合:

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

原文地址:https://www.jb51.cc/csharp/96871.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐