Distinct()方法不起作用?

时间:2015-05-14 15:38:41

标签: linq distinct duplication

我尝试使用Distinct()来过滤我的集合以防止重复,但我的linq查询仍然将相同的值添加到列表中。

提前感谢。

 public ObservableCollection<string> CollectTopicsFromXml()
    {
         ObservableCollection<string> oc = new ObservableCollection<string>();
         XDocument xDoc = XDocument.Load(path);
         var topicColl = xDoc.Descendants("topic").Distinct();


         foreach (var topic in topicColl)
         {
             oc.Add(topic.Value);
         }

        return oc;
    }

1 个答案:

答案 0 :(得分:1)

默认情况下,

Distinct使用引用相等性,除非在项类型上覆盖Equals(和GetHashCode)。由于Equals未覆盖XElement,因此无论其内容如何,​​每个元素都是“不同的”。

如果您想要Name或其他属性(或属性组合)的不同元素,您可以选择以下几个选项:

  • 将元素投影为匿名类型,默认情况下 实现值相等:

    var topicColl = xDoc.Descendants("topic")
                        .Select(e => new {e.Name, e.Value})
                        .Distinct();
    
  • 使用GroupBy,允许在

  • 中传递表达式
  • 以您希望的方式创建一个实现IEqualityComparer<XElement>的类,并将其传递给Distinct
  • 使用MoreLinq中的DistinctBy,它还允许在
  • 中传递相等表达式
相关问题