Linq 查询以获取唯一和排序



>我需要一个linq查询来获取唯一的对象列表,按Dep对它们进行分组并获取进度最高的值。我有一个对象列表,如下所示:

List<SomeObjects> lstObjects:
    lstObjects[0] - Dep: Marketing Comp:ABC  Progress: 1
    lstObjects[1] - Dep: Sales     Comp:ABC  Progress: 2
    lstObjects[2] - Dep: Marketing Comp:DEF  Progress: 2
    lstObjects[3] - Dep: Marketing Comp:DEF  Progress: 3
    lstObjects[4] - Dep: Sales     Comp:ABC  Progress: 1
    lstObjects[5] - Dep: Marketing Comp:ABC  Progress: 2
    lstObjects[6] - Dep: Marketing Comp:ABC  Progress: 1
    lstObjects[7] - Dep: Marketing Comp:ABC  Progress: 1

正如你所看到的 Dep: Marketing Comp:ABC,以不同的进度重复自己:,我必须获得具有最高进度的唯一对象列表。

    Eg: lstObjects[0] - Dep: Marketing Comp:ABC  Progress: 1
        lstObjects[5] - Dep: Marketing Comp:ABC  Progress: 2
        Here I should get, lstObjects[5] - Dep: Marketing Comp:ABC  Progress: 2
    In, lstObjects[2] - Dep: Marketing Comp:DEF  Progress: 2
        lstObjects[3] - Dep: Marketing Comp:DEF  Progress: 3
        In this I should get lstObjects[3] - Dep: Marketing Comp:DEF  Progress: 3
    In, lstObjects[1] - Dep: Sales     Comp:ABC  Progress: 2
        lstObjects[4] - Dep: Sales     Comp:ABC  Progress: 1
        In this I should get lstObjects[3] - Dep: Sales Comp:ABC  Progress: 2
        Finally my list should be:
        1)Dep: Marketing Comp:ABC  Progress: 2
        2)Dep: Marketing Comp:DEF  Progress: 3
        3)Dep: Sales     Comp:ABC  Progress: 2

提前谢谢。

您可以在

DepComp上使用GroupBy

var result = lstObjects
     .GroupBy(x=> new {x.Dep, x.Comp})
     .Select(x=> new 
      {
          Department = x.Key.Dep, 
          Comp = x.Key.Comp ,
          Progress =  x.Max(x => m.Progress)   
      });

GroupBy 2 属性应该可以工作:

List<SomeObjects> uniqueWithMax = (from rec in lstObjects
                                    group rec by new { rec.Dep, rec.Comp } into grp
                                    select new SomeObjects
                                    {
                                        Dep = grp.Key.Dep,
                                        Comp = grp.Key.Comp,
                                        Progress = grp.Max(x => x.Progress)
                                    }).ToList();

您首先按DeptComp分组。然后对于每组,取Progress最高的元素。后者可以通过多种方式实现,我最喜欢的 LINQ to Objects(缺少标准MaxBy)是线性时间使用 Aggregate 方法:

var result =
    (from e in lstObjects
     group e by new { e.Dep, e.Comp } into g
     select g.Aggregate((a, b) => b.Progress > a.Progress ? b : a))
    .ToList();
        var DepCompHighestProgress =
                      from d in lstObjects
                      group d by new { d.Dep, d.Comp } into oGrouped
                      select new
                      {
                          Dep = oGrouped.Key.Dep,
                          Comp = oGrouped.Key.Comp,
                          Progress = oGrouped.Max(depcomp => depcomp.Progress)
                      };

相关内容

  • 没有找到相关文章

最新更新