C# 从BindingList中删除重复项

C# 从BindingList中删除重复项,c#,distinct,ienumerable,enumerable,bindinglist,C#,Distinct,Ienumerable,Enumerable,Bindinglist,BindingList是否有删除重复元素的解决方案?我试过: BindingList<Account> accounts = new BindingList<Account>(); accounts.add(new Account("username", "password")); accounts.add(new Account("username", "password")); accounts = accounts.Distinct(); Bindin

BindingList是否有删除重复元素的解决方案?我试过:

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

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

 accounts = accounts.Distinct();
BindingList帐户=新建BindingList();
添加(新帐户(“用户名”、“密码”);
添加(新帐户(“用户名”、“密码”);
accounts=accounts.Distinct();
由于返回的是
System.Collections.Generic.IEnumerable
和not
BindingList
具有构造函数,该构造函数采用
IList
,您可以转换
可枚举的

BindingList指出使用默认的相等比较器

默认相等比较器default用于比较 实现IEquatable泛型接口的类型。到 比较自定义数据类型,您需要实现此接口和 为类型提供您自己的GetHashCode和Equals方法

试试这个:

foreach (var a in accounts
    .ToLookup(x => new { x.Username, x.Password })
    .SelectMany(x => x.Skip(1))
    .ToArray())
{
    accounts.Remove(a);
}

为什么不先确保它们是唯一的?@DanielA.White帐户是从文本文件加载的,用户可能会输入重复的条目。先检查有什么好处吗?可以将它们加载到字典/哈希集中。它们需要在绑定列表中。BindingList是DataGridView的数据源。这不会删除重复项。在Distinct之后对元素进行计数会显示相同的元素计数,即使存在重复项。@Torra这是因为您的
帐户
类没有覆盖
Equals
GetHashCode
@KingKing完全忘记了这样做。非常感谢。
foreach (var a in accounts
    .ToLookup(x => new { x.Username, x.Password })
    .SelectMany(x => x.Skip(1))
    .ToArray())
{
    accounts.Remove(a);
}