Group by in LINQ

后端 未结 10 1751
悲哀的现实
悲哀的现实 2020-11-21 06:58

Let\'s suppose if we have a class like:

class Person { 
    internal int PersonID; 
    internal string car; 
}

I have a list of this class

10条回答
  •  半阙折子戏
    2020-11-21 07:38

    Try this :

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

    But performance-wise the following practice is better and more optimized in memory usage (when our array contains much more items like millions):

    var carDic=new Dictionary>();
    for(int i=0;i(){person.car};
       }
    }
    //returns the list of cars for PersonId 1
    var carList=carDic[1];
    

提交回复
热议问题