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();
Expected output:
elements list should contain 3 items
<unit>CAN</unit>
<unit>KG</unit>
<unit>PKT</unit>
Distinct()does not know what part of theXElementto compare, so it will just compare the object reference. Since all XElements are separate objects, no matter the content, it will return them all.You either have to define an
IEqualityComparerthat 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;Output: