Distinct()不起作用
我有以下linq表达式:
AgentsFilter = new BindableCollection(( from firstEntry in FirstEntries select new NameValueGuid { Name = firstEntry.Agent, Value = firstEntry.AgentId }).Distinct() );
但由于某种原因,AgentsFilter Collection充满了重复。 我的Distinct()
什么问题?
Distinct
将使用NameValueGuid
上的Equals
方法查找重复项。 如果你不重写Equals
,那么它将检查引用。
您可以使用匿名类型添加额外的步骤以避免覆盖Equals。 匿名类型会自动覆盖Equals和GetHashCode以比较每个成员。 在匿名类型上执行distinct,然后将其投影到您的类上将解决问题。
from firstEntry in FirstEntries select new { Name = firstEntry.Agent, Value = firstEntry.AgentId }).Distinct().Select(x => new NameValueGuid { Name = x.Name, Value = x.Value });
您可能没有在NameValueGuid
上提供GetHashCode
和Equals
的实现。
或者,如果不可能,您可以将IEqualityComparer
的实例传递给您的Distinct
调用。
请参阅: http : //msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx
select new { Name = firstEntry.Agent, Value = firstEntry.AgentId }) .Distinct() .Select(x => new NameValueGuid { Name = x.Name, Value = x.Value });
您需要在具有Name
和Value
属性的类的上下文中定义Distinct
含义。 请参阅MSDN 。
尝试使用Distinct的重载来提供比较器。
例如:
AgentsFilter = new BindableCollection((from firstEntry in FirstEntries select new NameValueGuid { Name = firstEntry.Agent, Value = firstEntry.AgentId }) .Distinct((nvg) => nvg.Value) );
或者,如果您可以访问NameValueGuid的代码定义,则可以根据类重写GetHashCode
和Equals
。 再次,请参阅MSDN