假设我们有这样一个类:

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

有人能告诉我正确的方向吗?


当前回答

首先,设置关键字段。然后写上你的其他领域:

var results = 
    persons
    .GroupBy(n => n.PersonId)
    .Select(r => new Result {PersonID = r.Key, Cars = r.ToList() })
    .ToList()

其他回答

首先,设置关键字段。然后写上你的其他领域:

var results = 
    persons
    .GroupBy(n => n.PersonId)
    .Select(r => new Result {PersonID = r.Key, Cars = r.ToList() })
    .ToList()

当然,你基本上想要:

var results = from p in persons
              group p.car by p.PersonId into g
              select new { PersonId = g.Key, Cars = g.ToList() };

或作为非查询表达式:

var results = persons.GroupBy(
    p => p.PersonId, 
    p => p.car,
    (key, g) => new { PersonId = key, Cars = g.ToList() });

基本上,组的内容(当被视为IEnumerable<T>时)是给定键的投影(在本例中为p.car)中任何值的序列。

有关GroupBy如何工作的更多信息,请参阅我在Edulinq上关于该主题的帖子。

(我在上面将PersonID重命名为PersonID,以遵循. net命名约定,在“大写复合词和常用术语”一节中特别指出了这一点。)

或者,你也可以使用Lookup:

var carsByPersonId = persons.ToLookup(p => p.PersonId, p => p.car);

然后你可以很容易地得到每个人的车:

// This will be an empty sequence for any personId not in the lookup
var carsForPerson = carsByPersonId[personId];

try

persons.GroupBy(x => x.PersonId).Select(x => x)

or

检查是否有人在你的列表中重复出现

persons.GroupBy(x => x.PersonId).Where(x => x.Count() > 1).Any(x => x)
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()/**/}
var results = from p in persons
              group p by p.PersonID into g
              select new { PersonID = g.Key, Cars = g.Select(m => m.car) };