I tried to use Distinct() to filter my collection to prevent duplication but my linq query still adds the same values to list.
thanks in advance.
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;
}
Distinctby default uses reference equality unlessEquals(andGetHashCode) are overridden on the item type. SinceEqualsis not overridden forXElementeach element is "distinct" regardless of its contents.If you want distinct elements by
Nameor some other property (or combination of properties) you have a few options:Project the elements to an anonymous type which does implement value equality by default:
Use
GroupBy, which allows an expression to be passed inIEqualityComparer<XElement>in the way that you want and pass that toDistinctDistinctByfrom MoreLinq which also allows an equality expression to be passed in