LINQ group by List <results>并返回结果

时间:2017-08-13 05:18:45

标签: c# linq

我有三个List<Results>

var list1 = new List<Results> {
    new Results{ Empid = 1,Empname = "John",Rating = 1.33},
    new Results{ Empid = 2,Empname = "Aarya",Rating = 1.6},
    new Results{ Empid = 3,Empname = "Sansa",Rating = 1.6}
};

var list2 = new List<Results> {
    new Results{ Empid = 1,Empname = "John",Rating = 2.33},
    new Results{ Empid = 2,Empname = "Aarya",Rating = 2.6},
    new Results{ Empid = 3,Empname = "Sansa",Rating = 1.6}
};

var list3 = new List<Results> {
    new Results{ Empid = 1,Empname = "John",Rating = 0.33},
    new Results{ Empid = 2,Empname = "Aarya",Rating = 0.6}
};

我想要最终结果(基于Empid的所有评级的总和)

Final={Empid=1,Empname="John",Rating=3.99}
  {Empid=2,Empname="Aarya",Rating=4.8}
  {Empid=3,Empname="Sansa",Rating=3.2}

如何通过使用Linq实现这一点,我是LinQ的新手,我正在尝试使用GroupBy,但我无法做到。

3 个答案:

答案 0 :(得分:6)

使用Concat合并列表,然后通过以下方式合并普通组:

var result = list1.Concat(list2).Concat(list3)
                  .GroupBy(item => new { item.Empid, item.Empname }, item => item.Rating)
                  .Select(g => new { 
                      Id = g.Key.Empid, 
                      Name = g.Key.Empname, 
                      Rating = g.Sum() });

或者在查询语法中:

var result = from item in list1.Concat(list2).Concat(list3)
             group item.Rating by new { item.Empid, item.Empname } into g
             select new {
                 Id = g.Key.Empid,
                 Name = g.Key.Empname,
                 Rating = g.Sum()
             };

基于Empid 的所有评级的总和 - 请注意,如果id和名称相关,则最简单的方法是将它们中的两个分组,如上例所示。否则,按ID分组并为每个组检索.First().Empname

答案 1 :(得分:0)

首先你应该将所有列表连在一起,然后写下这样的东西:

var q = from p in concatlist
        group p by new { p.Empid, p.Empname} into g
        select new 
        {
           Empid = g.Key.Empid,
           Empname = g.Key.Empname,
           Rating = g.Sum(c=>c.Rating)
        };

答案 2 :(得分:0)

或者您可以使用Enumerable.SelectMany方法“拼合”列表,然后使用与其他答案相同的分组

var final = 
    new[] { list1, list2, list3 }.SelectMany(list => list)
                                 .GroupBy(result => new { result.EmpId, result.EmpName })
                                 .Select(group => new Results
                                 { 
                                     EmpId = group.Key.EmpId, 
                                     EmpName = group.Key.EmpName, 
                                     Rating = group.Sum(result => result.Rating) 
                                 });

使用SelectMany,您将能够查询动态数量的列表