I have a list with two or more objects of class Agent.
Name = “A”
Priority = 0
ResultCount = 100
;
Name = “B”
Priority = 1
ResultCount = 100
;
Both objects have the same ResultCount. In that case I only need one object and not two or more. I did this with a Linq Query with Distinct and an custom made Comparer.
IEnumerable<Agent> distinctResultsAgents =
(from agt in distinctUrlsAgents select agt).Distinct(comparerResultsCount);
With this query I get only one object from the list but I never know which one.
But I don’t want just any object, I want object “B” because the Priority is higher then object “A”.
How can I do that?
My custom Comparer is very simple and has a method like this:
public bool Equals(Agent x, Agent y)
{
if (x == null || y == null)
return false;
if (x.ResultCount == y.ResultCount)
return true;
return false;
}
First group the elements by
ResultCountso that you only get one result for each distinct value ofResultCount. Then for each group select the element in that group with the highest priority.Try this query:
If you use morelinq there is a function called MaxBy that you could use instead of the last line, but note that it only works for LINQ To Objects.