集团通过LINQ [英] Group by in LINQ
问题描述
让如果我们有像
class Person {
internal int PersonID;
internal string car ;
}
现在我有这个类的列表:列表<&人GT;人;
Now I have a list of this class: List<Person> persons;
现在这个名单可以有多个实例相同PersonIDs,为前。
Now this list can have instances multiple same PersonIDs, for ex.
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,并得到他的全部汽车的名单?
外汇。预计结果将是
Is there a way I can group by personID and get the list of all the cars he has? For ex. expected result would be
class Result {
int PersonID;
List<string> cars;
}
所以分组后我会得到:
So after grouping by I would get:
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
可能有人请点我朝着正确的方向?
Could someone please point me in the right direction?
推荐答案
当然 - 你基本上要:
Absolutely - you basically want:
var results = from p in persons
group p.car by p.PersonId into g
select new { PersonId = g.Key, Cars = g.ToList() };
,或作为非查询前pression:
Or as a non-query expression:
var results = persons.GroupBy( p => p.PersonId,
p => p.car,
(key, g) => new {
PersonId = key,
Cars = g.ToList()
}
);
组基本内容(当视图为的IEnumerable&LT; T&GT;
)是什么值的序列是在投影(点。汽车
在这种情况下)present给定键。
Basically the contents of the group (when view as an IEnumerable<T>
) is a sequence of whatever values were in the projection (p.car
in this case) present for the given key.
更多关于如何 GROUPBY
的作品,看到我的<一个href=\"http://$c$cblog.jonskeet.uk/2011/01/01/reimplementing-linq-to-objects-part-21-groupby/\">Edulinq张贴在话题。
For more on how GroupBy
works, see my Edulinq post on the topic.
(我已经改名为是PersonID
到 PERSONID
在上面,要遵循的.NET命名约定的。)
(I've renamed PersonID
to PersonId
in the above, to follow .NET naming conventions.)
这篇关于集团通过LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!