【问题标题】:How to check for the duplicates in an ObservableCollection?如何检查 ObservableCollection 中的重复项?
【发布时间】:2013-08-23 17:04:49
【问题描述】:

我有一个地址集合,其中有不同的地址项。每个地址项都有 AddressType、City、Zipcode 等列。我正在写一个验证,如果有人正在添加一个新的 addressType 并且 Addressses 的集合已经列出了一个 AddressType 然后给出一个警告它已经被列出。我怎样才能做到这一点。我附上了一些代码。现在它只检查它的“工作地址”。我有三种类型的地址。

       if (Addresses.Any
            (a => a.AddressType =="Job Address"))
        {
            DialogManager.ShowMessageBox(("The type has already been listed "),       
         MessageBoxButton.OKCancel);
        }

【问题讨论】:

    标签: c# linq collections


    【解决方案1】:

    如果你事后检查这个,你可以使用HashSet<string>的大小:

    var types = new HashSet<string>(Addresses.Select(aa => aa.AddressType));
    if (types.Count < Addresses.Count)
    {
        // You have a duplicate...
        // ...not necessarily easy to know WHO is the duplicate
    }
    

    上面的工作是通过将每个AddressType 实例分配给一个集合来实现的。集合是仅包含添加的唯一项目的集合。因此,如果您的输入序列中有重复项,则该集合将包含比您的输入序列更少的项目。您可以这样说明这种行为:

    // And an ISet<T> of existing items
    var types = new HashSet<string>();
    
    foreach (string typeToAdd in Addresses.Select(aa => aa.AddressType))
    {
        // you can test if typeToAdd is really a new item
        // through the return value of ISet<T>.Add:
        if (!types.Add(typeToAdd))
        {
            // ISet<T>.Add returned false, typeToAdd already exists
        }
    }
    

    如果您以类似的方式实现它,则可能是通过命令的CanExecute 提前实现更好的方法:

    this.AddCommand = new DelegateCommand<Address>(
        aa => this.Addresses.Add(aa),
        aa => !this.Addresses.Any(xx => xx.AddressType == aa.AddressType));
    

    【讨论】:

    • 感谢第一个工作。我仍然不确定如何。你能解释一下这是如何工作的吗?
    • @C_looksharp:我已经更新了我的答案,为您提供了更多详细信息。
    【解决方案2】:

    创建一个新的AddressComparer 类实现IEqualityComparer 接口

    现在你使用Contains 方法

    if(Addresses.Contains(Address,new AddressComparer()))
    {
          //your code
    }
    

    【讨论】:

    • 您还需要在 Address 类上重写 Equals(),以定义“相同地址”的确切含义。默认情况下,它表示“内存中的相同位置”;默认情况下,内容完全相同的两个不同的 Address 对象将不相等。
    猜你喜欢
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    • 2020-08-25
    • 2017-08-02
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多