我有一个项目列表
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
秒
通过此示例,要返回的项目为itemf
和MinorV
。
我在下面有一个查询,但没有考虑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');
有什么想法吗?
答案 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();
答案 2 :(得分:0)
基于德米特里·拜琴科的答案& Stefan Steinegger评论此查询是最简单的并且有效:
var filteredquery = query
.GroupBy(x => x.Id)
.Select(chunk => chunk
.OrderByDescending(item => item.MajorV)
.ThenByDescending(item => item.MinorV)
.First())
.ToList();