群由In 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谁能帮我指出正确的方向吗?
3 回答
Cats萌萌
TA贡献1805条经验 获得超9个赞
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()/**/}
元芳怎么了
TA贡献1798条经验 获得超7个赞
var results = from p in persons group p by p.PersonID into g select new { PersonID = g.Key, Cars = g.Select(m => m.car) };
- 3 回答
- 0 关注
- 544 浏览
添加回答
举报
0/150
提交
取消