C# 从BindingList中删除重复项
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<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
和notBindingList
具有构造函数,该构造函数采用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);
}