I implemented IEqualityComparer and IEquatable (both to be sure), but when I call the Distinct () method on the collection, it does not call the methods that come with it. Here is the code that I execute when I call the Distinct () function.
ObservableCollection<GigViewModel> distinctGigs = new ObservableCollection<GigViewModel>(Gigs.Distinct<GigViewModel>()); return distinctGigs;
I want to return an ObservableCollection that does not contain any double objects found in the ObservableCollection 'Gigs' collection.
I implement such interfaces in the GigViewModel class:
public class GigViewModel : INotifyPropertyChanged, IEqualityComparer<GigViewModel>, IEquatable<GigViewModel> { .... }
And override the methods that come with such interfaces:
public bool Equals(GigViewModel x, GigViewModel y) { if (x.Artiest.Naam == y.Artiest.Naam) { return true; } else { return false; } } public int GetHashCode(GigViewModel obj) { return obj.Artiest.Naam.GetHashCode(); } public bool Equals(GigViewModel other) { if (other.Artiest.Naam == this.Artiest.Naam) { return true; } else { return false; } }
Thanks for all the help I get. So I created a separate class that implements IEqualityComparer and passed it to the instance in the disctinct method. But the methods are still not starting.
EqualityComparer:
class GigViewModelComparer : IEqualityComparer<GigViewModel> { public bool Equals(GigViewModel x, GigViewModel y) { if (x.Artiest.Naam == y.Artiest.Naam) { return true; } else { return false; } } public int GetHashCode(GigViewModel obj) { return obj.Artiest.Naam.GetHashCode(); } }
Call Distinct() :
GigViewModelComparer comp = new GigViewModelComparer(); ObservableCollection<GigViewModel> distinctGigs = new ObservableCollection<GigViewModel>(Gigs.Distinct(comp)); return distinctGigs;
EDIT2:
GetHashCode() Method GetHashCode() WIN! After introducing a new class. But the collection still contains duplicates. I have a "Gigs" list that contains an "Artiest" (or Artist) object. This artist has a Naam property, which is a string (Name).
c # windows-phone silverlight windows-phone-8 observablecollection
Tim kranen
source share