开发者

Need help with this basic Contains<>() extension method and Lambda expressions

Say I have the following class:

class Foo
{
    // ctor etc here

    publ开发者_高级运维ic 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


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+.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜