Distinct() doesn't work

独自空忆成欢 提交于 2019-12-29 05:20:51

问题


I have the following linq expression:

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

But because of some reason, the AgentsFilter Collection is full of duplicates. What is wrong with my Distinct()?


回答1:


Distinct will use the Equals method on NameValueGuid to find duplicates. IF you do not override Equals, then it will check references.

You can add an extra step to avoid overriding Equals, by using an anonymous type. Anonymous types automatically override Equals and GetHashCode to compare each member. Doing the distinct on the anonymous type, then projecting that onto your class will solve the problem.

from firstEntry in FirstEntries
select new
{ 
    Name = firstEntry.Agent,
    Value = firstEntry.AgentId
}).Distinct().Select(x => new NameValueGuid
{
    Name = x.Name,
    Value = x.Value
});



回答2:


You might not have supplied an implementation of both GetHashCode and Equals on NameValueGuid.

Alternatively, if that isn't possible, you can pass an instance of IEqualityComparer<NameValueGuid> to your call of Distinct.

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




回答3:


select new
{ 
    Name = firstEntry.Agent,
    Value = firstEntry.AgentId
})
.Distinct()
.Select(x => new NameValueGuid
{
    Name = x.Name,
    Value = x.Value
});



回答4:


You need to define what Distinct means in the context of a class with Name and Value properties. See MSDN.

Try the overload of Distinct that lets you provide a comparer.

For example:

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

Alternatively, if you have access to the code definition of NameValueGuid, then you can override GetHashCode and Equals as appropriate for the class. Again, see MSDN



来源:https://stackoverflow.com/questions/11884255/distinct-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!