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
With this example the items to be returned are itemc
and itemf
.
I have a query of below, but does not take into account the 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:
var filteredquery = query
.GroupBy(x => x.Id)
.Select(chunk => chunk
.OrderByDescending(item => item.MajorV)
.ThenByDescending(item => item.MinorV)
.First())
.ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.