发布于 4年前

LINQ group by的使用示例

下面通过一个示例来展示linq中group by的使用。

类Person如下:

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

Person列表List<Person>:

persons[0] = new Person { PersonID = 1, car = "Ferrari" }; 
persons[1] = new Person { PersonID = 1, car = "BMW"     }; 
persons[2] = new Person { PersonID = 2, car = "Audi"    }; 

对Person进行分组

方法一:使用查询表达select

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

方法二:非查询表达,直接使用GroupBy

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

得到结果如下:

results[0].PersonId = 1; 
List<string> cars = results[0].cars; 
result[1].PersonId = 2; 
List<string> cars = result[1].cars;

替代方案:Lookup

如果是简单获取指定person的cars列表,可以使用Lookup方法:

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

获取cars列表

var carsForPerson = carsByPersonId[personId];
©2020 edoou.com   京ICP备16001874号-3