tags:

views:

71

answers:

1

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;
    } 
+5  A: 

First group the elements by ResultCount so that you only get one result for each distinct value of ResultCount. Then for each group select the element in that group with the highest priority.

Try this query:

IEnumerable<Agent> distinctResultsAgents =
    from d in distinctUrlsAgents
    group d by d.ResultCount into g
    select g.OrderByDescending(x => x.Priority).First();

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.

Mark Byers
FirstOrDefault -- if the collection is empty
tvanfosson
@tvanfosson: I don't think it is necessary to use FirstOrDefault here. If the collection is empty there will be no groups so First will not be called.
Mark Byers
@Mark - ah, yes, Select is operating on the enumeration of `IGrouping<TKey,TSource>` and the orderby/first is applied to each of these in the collection, not to the enumeration itself. Sorry for the mistake.
tvanfosson