Search code examples
c#distinctienumerableenumerablebindinglist

Remove Duplicates From BindingList


Does BindingList have any solution to remove duplicate elements? I've tried:

 BindingList<Account> accounts = new BindingList<Account>();

 accounts.add(new Account("username", "password"));
 accounts.add(new Account("username", "password"));

 accounts = accounts.Distinct();

The above does not work as Distinct is returning System.Collections.Generic.IEnumerable<T> and not BindingList<T>


Solution

  • BindingList has a Constructor which takes an IList<T> and you can convert an Enumerable<T> to a List.

    BindingList<Account> distinctAccounts = new BindingList<Account>(accounts.Distinct().ToList());
    

    As King King points out Distinct() uses the default equality comparer

    The default equality comparer, Default, is used to compare values of the types that implement the IEquatable generic interface. To compare a custom data type, you need to implement this interface and provide your own GetHashCode and Equals methods for the type.