使用LINQ选择唯一项目

Asa*_*saf 4 c# linq distinct

当我使用以下代码时,我多次获得相同的项目.

XElement neededFiles = new XElement("needed",
    from o in _9nFiles.Elements()
    join t in addedToSitePull.Elements()
         on o.Value equals
         t.Value
    where o.Value == t.Value
    select new XElement("pic", o.Value));
Run Code Online (Sandbox Code Playgroud)

我想只获得独特的物品.我看到了Stack Overflow帖子,如何用LINQ做SELECT UNIQUE?,使用它,我试图实现它,但改变没有影响.

代码:

XElement neededFiles = new XElement("needed",
(from o in _9nFiles.Elements()
join t in addedToSitePull.Elements()
on o.Value equals
 t.Value
 where o.Value == t.Value
select new XElement("pic", o.Value)).Distinct() );
Run Code Online (Sandbox Code Playgroud)

Lee*_*Lee 7

我想这不起作用的原因是因为XElement.Equals使用简单的引用相等性检查而不是比较Value两个项的属性.如果要比较值,可以将其更改为:

_9nfiles.Elements()
    .Join(addedToSitePull, o => o.Value, t => t.Value, (o, t) => o.Value)
    .Distinct()
    .Select(val => new XElement("pic", val));
Run Code Online (Sandbox Code Playgroud)

您也可以创建自己的值IEqualityComparer<T>来比较两个XElement值.请注意,这假设所有值都为非null:

public class XElementValueEqualityComparer : IEqualityComparer<XElement>
{
    public bool Equals(XElement x, XElement y)
    {
        return x.Value.Equals(y.Value);
    }

    public int GetHashCode(XElement x)
    {
        return x.Value.GetHashCode();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,你可以取代现有的呼叫DistinctDistinct(new XElementValueEqualityComparer()).