[英]LINQ - GroupBy Item and filter based on two Properties
I have a list of items 我有项目清单
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 };
And I want to create a linq query to return a list of unique ids
which have the highest MajorV
first and then the highest MinorV
second 我想创建一个linq查询以返回唯一
ids
的列表,这些ids
首先具有最高的MajorV
,然后具有最高的MinorV
With this example the items to be returned are itemc
and itemf
. 在此示例中,要返回的项目为
itemc
和itemf
。
I have a query of below, but does not take into account the MinorV
我有以下查询,但未考虑
MinorV
var filteredquery = query.GroupBy(cm => new { cm.Id })
.Select(grp => grp.Aggregate((max, cur) =>
(max == null || cur.MajorV > max.MajorV) ? cur : max));
Any thoughts? 有什么想法吗?
var filteredquery = query.GroupBy(cm => cm.Id)
.Select(gcm => gcm.OrderByDescending(cm => cm.MajorV).OrderByDescending(cm => cm.MinorV).First());
This is giving me the result you expect:- 这给了我您期望的结果:
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();
Based on Dmitry Bychenko answer & Stefan Steinegger comment this query is the simplest and works: 基于Dmitry Bychenko答案和Stefan Steinegger的评论,此查询最简单且有效:
var filteredquery = query
.GroupBy(x => x.Id)
.Select(chunk => chunk
.OrderByDescending(item => item.MajorV)
.ThenByDescending(item => item.MinorV)
.First())
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.