Search code examples
c#uniquedistinctobservablecollection

C# ObservableCollection<T> Distinct not as expected


From what I've read on Stack and other resources, this should yield a distinct collection of objects (essentially unique), however, that's not what I'm observing as a result. Any help would be appreciated.

ObservableCollection<CompanySummary> companies = 
   new ObservableCollection<CompanySummary>(DispatchListOriginal.Select(
   x => new CompanySummary { CompanyName = x.CompanyName, CompanyId = x.CompanyId })
   .Distinct());

(all of the above is on one line)

I've also tried this:

ObservableCollection<CompanySummary> companies = new ObservableCollection<CompanySummary>(DispatchListOriginal.Select(x => new CompanySummary { CompanyName = x.CompanyName, CompanyId = x.CompanyId }));
CompanyList = new ObservableCollection<CompanySummary>(companies.Distinct());

The result in both cases is a collection of CompanySummary objects however, there are duplicates.


Solution

  • Distinct uses the Equals method.
    Make sure that CompanySummary.Equals does what it should do.