开发者

How to pick a specific object from a Linq Query using Distinct?

开发者 https://www.devze.com 2022-12-30 16:06 出处:网络
I have a list with two or more objects of class Agent. Name = \"A\" Priority = 0 ResultCount = 100 ; Name = \"B\"

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开发者_如何学C 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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消