在LINQ中分组

假设我们有类似的课程

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

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


绝对 - 你基本上想要:

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文章。

(我在上面将PersonID重命名为PersonId ,以遵循.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];

var results = from p in persons
              group p by p.PersonID into g
              select new { PersonID = g.Key,
                           /**/car = g.Select(g=>g.car).FirstOrDefault()/**/}

var results = from p in persons
              group p by p.PersonID into g
              select new { PersonID = g.Key, Cars = g.Select(m => m.car) };
链接地址: http://www.djcxy.com/p/5857.html

上一篇: Group by in LINQ

下一篇: What is the Java equivalent for LINQ?