Distinct()不起作用

Dav*_*het 13 .net c# linq distinct

我有以下linq表达式:

AgentsFilter = new BindableCollection<NameValueGuid>((
    from firstEntry in FirstEntries
    select new NameValueGuid { 
        Name = firstEntry.Agent,
        Value = firstEntry.AgentId
    }).Distinct()
);
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,AgentsFilter Collection充满了重复.我有什么问题Distinct()

cad*_*ll0 33

Distinct将使用该Equals方法NameValueGuid来查找重复项.如果你没有覆盖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
});
Run Code Online (Sandbox Code Playgroud)


stu*_*ith 8

你可能没有提供双方的实施GetHashCodeEqualsNameValueGuid.

或者,如果无法做到这一点,您可以将一个实例传递IEqualityComparer<NameValueGuid>给您Distinct.

请参阅:http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx

  • +1,没有意识到我还需要重写“GetHashCode”才能使“Distinct”工作。重写后,看来`Distinct`首先调用`GetHashCode`来确定是否需要调用`Equals`。 (2认同)