所以我有一个简单的类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
中的汽车列表?
答案 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)
});