Chit Khine Chit Khine - 2 days ago 5
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
BaseItem{
Id,
Type,
Rating,
}


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

Rob Rob
Answer

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 => e.id)
                  .Select(g => 
                      g.OrderByDescending(e => e.Rating).First()
                  );
Comments