【问题标题】:Remove Duplicates From BindingList从 BindingList 中删除重复项
【发布时间】:2013-12-17 15:12:19
【问题描述】:

BindingList 是否有任何解决方案来删除重复元素?我试过了:

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

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

 accounts = accounts.Distinct();

上述方法不起作用,因为 Distinct 返回的是 System.Collections.Generic.IEnumerable&lt;T&gt; 而不是 BindingList&lt;T&gt;

【问题讨论】:

  • 你为什么不首先确保它们是唯一的?
  • @DanielA.White 帐户是从文本文件加载的,用户可能会输入重复的条目。先检查有什么好处吗?
  • 您可以将它们加载到字典/哈希集中。
  • 它们需要在一个 BindingList 中。 BindingList 是 DataGridView 的 DataSource。

标签: c# distinct ienumerable enumerable bindinglist


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    BindingList 有一个构造函数,它接受 IList&lt;T&gt;,您可以转换 Enumerable&lt;T&gt; to a List

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

    正如King King 指出的Distinct() 使用默认的相等比较器

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

    【讨论】:

    • 这不会删除重复项。在 Distinct 之后对元素进行计数显示相同的元素计数,即使存在重复项。
    • @Torra 这是因为你的 Account 类没有覆盖 EqualsGetHashCode
    • @KingKing 完全忘记了这样做。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 2015-09-30
    • 2018-08-21
    • 1970-01-01
    • 2015-10-11
    • 2010-09-19
    相关资源
    最近更新 更多