C_sharp
C_sharp

Reputation: 418

How to check for the duplicates in an ObservableCollection?

I have a collection of Addresses, which has different address items. Each address item has AddressType, City, Zipcode and other columns. I am writing a validation that if some one is adding a new addressType and the collection of Addressses has already an AddressType listed then give a warning that it has already been listed. How can I do that. I have attached some code. Right now its only checking it for the "Job Address". I have three types of Addresss.

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

Upvotes: 2

Views: 3603

Answers (2)

user7116
user7116

Reputation: 64078

If you are checking this after the fact, you can use the size of a 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
}

The above works by assigning each of the AddressType instances to a set. A set is a collection which only contains the unique items added. Therefore, if you have duplicates in your input sequence, the set will contain less items than your input sequence. You can illustrate this behavior like so:

// 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
    }
}

A better way would be beforehand, perhaps through CanExecute of a command if you have it implemented in a similar fashion:

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

Upvotes: 1

Anirudha
Anirudha

Reputation: 32797

Create a new AddressComparer class implementing IEqualityComparer interface

Now you use Contains method

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

Upvotes: 1

Related Questions