假设我们有一个类似的类:
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
有人能指出我正确的方向吗?
Count
,Sum
这里包括stackoverflow.com/questions/3414080/…–