LINQ Group by具有多个值

时间:2018-10-26 07:10:11

标签: linq group-by

所以我有一个简单的类Person

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

我想按PersonID分组,以便获得所有汽车的清单和所有计数的总和:

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

我知道如何分组和创建求和:

var sums = from foo in persons
       group foo by foo.PersonID into groupings

       select new Result
       {
           PersonID = groupings.Key,               
           sum = groupings.Sum(g => g.count)
       };

但是如何创建Result中的汽车列表?

1 个答案:

答案 0 :(得分:2)

这可能是anonymous class的一个示例,但对于Result应该是相同的:

List<Person> p = new List<Person>
{
    new Person {PersonID = 1, car = "Audo", count = 1},
    new Person {PersonID = 1, car = "Bmw", count = 2},
    new Person {PersonID = 1, car = "Reno", count = 3},
    new Person {PersonID = 2, car = "Audi", count = 1},
    new Person {PersonID = 3, car = "Audi", count = 1},
};

var res = p.GroupBy(i => i.PersonID).Select(g =>
    new {
            ID = g.Key, 
            Cars = g.Select(_ => _.car).ToList(), 
            Count = g.Sum(_ => _.count)
    });