XDocument 使用 LINQ 选择不同的元素 [英] XDocument select distinct elements using LINQ
问题描述
我试图获取一个独特的元素列表,但它总是返回所有内容.
I am trying to get a distinct list of elements but it always returns everything.
Xml:
<root>
<row>
<unit>CAN</unit>
</row>
<row>
<unit>KG</unit>
</row>
<row>
<unit>KG</unit>
</row>
<row>
<unit>PKT</unit>
</row>
<row>
<unit>CAN</unit>
</row>
<row>
<unit>PKT</unit>
</row>
<row>
<unit>KG</unit>
</row>
</root>
Linq:
List<XElement> elements = (from e in xdoc.Descendants("row").Elements()
where e.Name.Equals("unit")
select e).Distinct().ToList();
预期输出:元素列表应包含3个项目
Expected output: elements list should contain 3 items
<unit>CAN</unit>
<unit>KG</unit>
<unit>PKT</unit>
推荐答案
Distinct()
不知道要比较 XElement
的哪一部分,所以它只会进行比较对象引用.由于所有XElement都是单独的对象,因此无论内容如何,它都将全部返回.
Distinct()
does not know what part of the XElement
to compare, so it will just compare the object reference. Since all XElements are separate objects, no matter the content, it will return them all.
您必须定义 IEqualityComparer
允许它比较它们(可能是首选方法),或者只是使用可以占用lambda的GroupBy来代替它来比较实际值;
You either have to define an IEqualityComparer
that allows it to compare them (probably the preferred way to do it) or just use GroupBy that can take a lambda that will allow it to compare the actual Value instead;
var elements = (from e in xdoc.Root.Elements("row").Elements("unit")
select e).GroupBy(x => x.Value).Select(x => x.First());
输出:
<unit>CAN</unit>
<unit>KG</unit>
<unit>PKT</unit>
这篇关于XDocument 使用 LINQ 选择不同的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!