FlySwat FlySwat - 1 year ago 69
C# Question

Checking for duplicates in a collection

Suppose you have a collection of


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

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

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?

Answer Source
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.