假设我们有这样一个类:

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 = 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= persons.GroupBy(n => n.PersonId)
            .Select(g => new {
                           PersonId=g.Key,
                           Cars=g.Select(p=>p.car).ToList())}).ToList();

但在性能方面,下面的做法在内存使用方面更好,更优化(当我们的数组包含更多的项,如数百万):

var carDic=new Dictionary<int,List<string>>();
for(int i=0;i<persons.length;i++)
{
   var person=persons[i];
   if(carDic.ContainsKey(person.PersonId))
   {
        carDic[person.PersonId].Add(person.car);
   }
   else
   {
        carDic[person.PersonId]=new List<string>(){person.car};
   }
}
//returns the list of cars for PersonId 1
var carList=carDic[1];
var results = from p in persons
              group p by p.PersonID into g
              select new { PersonID = g.Key, Cars = g.Select(m => m.car) };

下面的示例使用GroupBy方法返回按PersonID分组的对象。

var results = persons.GroupBy(x => x.PersonID)
              .Select(x => (PersonID: x.Key, Cars: x.Select(p => p.car).ToList())
              ).ToList();

Or

 var results = persons.GroupBy(
               person => person.PersonID,
               (key, groupPerson) => (PersonID: key, Cars: groupPerson.Select(x => x.car).ToList()));

Or

 var results = from person in persons
               group person by person.PersonID into groupPerson
               select (PersonID: groupPerson.Key, Cars: groupPerson.Select(x => x.car).ToList());

或者你可以使用ToLookup,基本上ToLookup使用EqualityComparer<TKey>。默认比较键,并执行在使用group by和to dictionary时应该手动执行的操作。 我认为它是在内存中执行的

 ILookup<int, string> results = persons.ToLookup(
            person => person.PersonID,
            person => person.car);

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()/**/}