tags:

views:

181

answers:

2

Hi,

Say I have the following class:

class Foo
{
    // ctor etc here

    public string Bar
    {
        get;
    }
}

Now, I have a LinkedList of Foos declared like so: LinkedList<Foo>

How would I write a basic Contains<>() for this?

I want to be able to do this:

Foo foo = new Foo(someString);
LinkedList<Foo> list = new LinkedList<foo>();

// Populate list with Foos

bool contains = list.Contains<Foo>(foo, (x => foo.Bar == x.Bar));

Am I trying to do this correctly?

Thanks

+4  A: 

If you want to use LinkedList.Contains, you can do that, but Foo but implement IEquatable<Foo>. LinkedList.Contains does not work via a Predicate function, but rather by searching for a specific element. To use Contains, you would write:

bool contains = list.Contains(foo);

However, in this case, you may want to consider using the Enumerable.Any() extension method instead of Contains(). Doing this, it will look like your previous code, except you don't need the first "foo":

Foo foo = new Foo(someString);
LinkedList<Foo> list = new LinkedList<foo>();

// Populate list with Foos

bool contains = list.Any(x => foo.Bar == x.Bar);

Since "foo" is visible in the current scope, when you create the lambda expression, the compiler will automatically generate a closure over the "foo" variable, allowing you to use it directly. You only need to specify the argument name (x) for use in the predicate function created in the lambda.

This requires a reference to System.Core.dll and a using System.Linq; at the top of your file, as well as .NET 3.5+.

Reed Copsey
Then what is that Contains<>() method for?? I guess thats what I'm confused on haha. Thanks
Polaris878
@Polaris878: Contains works, too - I just reworded to be more clear. However, contains works differently. Instead of using a Predicate, it searches for a specific element, using the normal equality checking. It's useful if you are seeing if that specific "foo" is in your list...
Reed Copsey
+5  A: 

What you want is .Any<T>() in this case. Something like this:

bool contains = list.Any(x => foo.Bar == x.Bar);

What this says is "are there any where this statement is true?" Think Count() > 0 in this case. Then you use a variable, in this case x, x stands for the current element in list that you are on while iterating through it, so for each element you're comparing and seeing if it matches.

Nick Craver