假设我有以下类(class):
class Foo
{
// ctor etc here
public string Bar
{
get;
}
}
现在,我有一个 LinkedList
的 Foo
s 声明如下:LinkedList<Foo>
我将如何为此编写一个基本的 Contains<>()?
我希望能够做到这一点:
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));
我是否尝试正确执行此操作?
谢谢
最佳答案
如果你想使用LinkedList.Contains , 你可以这样做,但是 Foo
但实现 IEquatable<Foo>
. LinkedList.Contains不通过 Predicate 函数工作,而是通过搜索特定元素工作。要使用 Contains,您可以这样写:
bool contains = list.Contains(foo);
但是,在这种情况下,您可能需要考虑使用 Enumerable.Any()扩展方法而不是 Contains()。这样做,它看起来就像您以前的代码,除了您不需要第一个“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);
由于“foo”在当前范围内可见,当您创建 lambda 表达式时,编译器会自动在“foo”变量上生成一个闭包,让您可以直接使用它。您只需指定参数名称 (x) 即可在 lambda 中创建的谓词函数中使用。
这需要引用 System.Core.dll 和 using System.Linq;
在文件的顶部,以及 .NET 3.5+。
关于c# - 在这个基本的 Contains<>() 扩展方法和 Lambda 表达式方面需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2568887/