小编典典

在LINQ中分组

c#

假设我们有一个类似的类:

class Person { 
    internal int PersonID; 
    internal string car; 
}

现在,我有一个此类的清单: List<Person> persons;

现在,此列表可以包含多个具有相同PersonID的实例,例如:

persons[0] = new Person { PersonID = 1, car = "Ferrari" }; 
persons[1] = new Person { PersonID = 1, car = "BMW"     }; 
persons[2] = new Person { PersonID = 2, car = "Audi"    };

我有办法分组PersonID并获得他拥有的所有汽车的清单吗?

例如,预期结果将是

class Result { 
   int PersonID;
   List<string> cars; 
}

因此,分组后,我会得到:

results[0].PersonID = 1; 
List<string> cars = results[0].cars;

result[1].PersonID = 2; 
List<string> cars = result[1].cars;

从我到目前为止所做的事情来看:

var results = from p in persons
              group p by p.PersonID into g
              select new { PersonID = g.Key, // this is where I am not sure what to do

有人能指出我正确的方向吗?


阅读 279

收藏
2020-05-19

共1个答案

小编典典

绝对-您基本上想要:

var results = from p in persons
              group p.car by p.PersonId into g
              select new { PersonId = g.Key, Cars = g.ToList() };

或作为非查询表达式:

var results = persons.GroupBy(
    p => p.PersonId, 
    p => p.car,
    (key, g) => new { PersonId = key, Cars = g.ToList() });

基本上,该组的内容(当视为时IEnumerable<T>)是p.car给定键在投影中(在这种情况下)呈现的任何值的序列。

有关如何GroupBy工作的更多信息,请参阅我在Edulinq上有关该主题的帖子

(在上文中,我已重命名PersonIDPersonId,以遵循.NET命名约定。)

另外,您可以使用Lookup

var carsByPersonId = persons.ToLookup(p => p.PersonId, p => p.car);

然后,您可以非常轻松地为每个人购买汽车:

// This will be an empty sequence for any personId not in the lookup
var carsForPerson = carsByPersonId[personId];
2020-05-19