LINQ - GroupBy项目和过滤器基于两个属性

时间:2015-08-20 08:10:29

标签: c# linq

我有一个项目列表

var itema = new ObjX { Id = 1, MajorV = 1, MinorV = 1 };
var itemb = new ObjX { Id = 1, MajorV = 2, MinorV = 1 };
var itemc = new ObjX { Id = 1, MajorV = 3, MinorV = 0 };
var iteme = new ObjX { Id = 2, MajorV = 2, MinorV = 0 };
var itemf = new ObjX { Id = 2, MajorV = 2, MinorV = 1 };

我想创建一个linq查询,以返回唯一ids列表,其中MajorV首先是MinorV,然后是最高itemc

通过此示例,要返回的项目为itemfMinorV

我在下面有一个查询,但没有考虑var filteredquery = query.GroupBy(cm => new { cm.Id }) .Select(grp => grp.Aggregate((max, cur) => (max == null || cur.MajorV > max.MajorV) ? cur : max));

$this->request->session()->read('Auth.User');

有什么想法吗?

3 个答案:

答案 0 :(得分:0)

var filteredquery = query.GroupBy(cm => cm.Id)
                .Select(gcm => gcm.OrderByDescending(cm => cm.MajorV).OrderByDescending(cm => cm.MinorV).First());

答案 1 :(得分:0)

这给了我预期的结果: -

var result = items.GroupBy(x => x.Id)
                  .Select(x => 
                  {
                     var CriteriaObj = x.OrderByDescending(z => z.MajorV)
                                        .ThenByDescending(z => z.MinorV).First();
                     return new ObjX
                            {
                                Id = x.Key,
                                MajorV = CriteriaObj.MajorV,
                                MinorV = CriteriaObj.MinorV
                            };
                  }).ToList();

Working Fiddle.

答案 2 :(得分:0)

基于德米特里·拜琴科的答案& Stefan Steinegger评论此查询是最简单的并且有效:

       var filteredquery = query
                           .GroupBy(x => x.Id)
                           .Select(chunk => chunk
                               .OrderByDescending(item => item.MajorV)
                               .ThenByDescending(item => item.MinorV)
                               .First())
                           .ToList();