Search code examples
c#.net.net-2.0

Checking for duplicates in a collection


Suppose you have a collection of Foo classes:

class Foo
{
    public string Bar;
    public string Baz;
}

List<Foo> foolist;

And you want to check this collection to see if another entry has a matching Bar.

bool isDuplicate = false;
foreach (Foo f in foolist)
{
     if (f.Bar == SomeBar)
     {
         isDuplicate = true;
         break;
     }
}

Contains() doesn't work because it compares the classes as whole.

Does anyone have a better way to do this that works for .NET 2.0?


Solution

  • fooList.Exists(item => item.Bar == SomeBar)
    

    That's not LINQ, but a Lambda expression, but nevertheless, it uses a v3.5 feature. No problem:

    fooList.Exists(delegate(Foo Item) { return item.Bar == SomeBar});
    

    That should work in 2.0.