【问题标题】:LINQ Select distinct from a List?LINQ Select 不同于列表?
【发布时间】:2011-09-27 15:50:18
【问题描述】:

我有以下清单:

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"

【问题讨论】:

  • 你的意思是姓氏!=城市吗?
  • 不,我不想要一个包含所有包含 1 作为城市和另一个包含 2 作为城市的 Persons 的列表...
  • 您是否要按城市对该人进行分组?
  • 我也很困惑。您是想按城市统计人数,还是按城市分组?

标签: c# linq


【解决方案1】:

您可以使用 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);
    }
}

【讨论】:

    【解决方案2】:

    除了达林·迪米特洛夫的回答,这里的查询语法是一样的:

    var groupByCityQuery = from person in personList 
                           group person by person.City into grouping 
                           select grouping;
    

    【讨论】:

      【解决方案3】:

      从这个评论来看:不,我不想一个包含所有包含 1 作为城市和另一个包含 2 作为城市的 Persons 的列表......

      我们可以这样做:

      var city1People = personList.Where(x => x.city == "1").ToList();
      var city2People = personList.Where(x => x.city == "2").ToList();
      

      如果这是更动态的东西,例如您将拥有 N 个城市并且想要每个城市的个人列表,您将需要返回列表集合。

      【讨论】:

      • 我怎样才能动态地做到这一点?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多