Chit Khine Chit Khine - 1 year ago 62
C# Question

how to select the highest rating item if the Ids are the same (distinct)?

I have two lists which contains the Id, Type and Rating.
I union those two lists and distinct them by Id using moreLinq. However, I am getting the rating which is added to the list later. I would like to be able to distinct them with Id and get the item which have the most rating.

item1.Union(item2).DistinctBy(e => e.Id);
where item1 is a baseItem of

It is always giving me the ratings of item2 if their Ids are the same.

Rob Rob
Answer Source

You can group, order, and take the first item (and you don't need MoreLinq for this anymore):

var result = item1.Union(item2)
                  .GroupBy(e =>
                  .Select(g => 
                      g.OrderByDescending(e => e.Rating).First()