[英]How to pick a specific object from a Linq Query using Distinct?
I have a list with two or more objects of class Agent. 我有一个列表,其中包含两个或多个Agent类的对象。
Name = "A" 名称=“ A”
Priority = 0 优先级= 0
ResultCount = 100 ResultCount = 100
; ;
Name = "B" 名称=“ B”
Priority = 1 优先级= 1
ResultCount = 100 ResultCount = 100
; ;
Both objects have the same ResultCount. 这两个对象具有相同的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. 我使用具有唯一性的Linq查询和定制的比较器来完成此操作。
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". 但是我不想要任何对象,我想要对象“ B”,因为优先级高于对象“ 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 ResultCount
so that you only get one result for each distinct value of ResultCount
. 首先,将元素按ResultCount
分组,以使每个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. 如果使用morelinq ,则可以使用一个名为MaxBy的函数代替最后一行,但是请注意,该函数仅适用于LINQ To Objects。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.