Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for duplicates in a collection

Tags:

c#

.net

.net-2.0

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?

like image 812
FlySwat Avatar asked Dec 13 '22 06:12

FlySwat


1 Answers

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.

like image 138
James Curran Avatar answered Dec 27 '22 08:12

James Curran