IEnumerable <T>.包含谓词

aba*_*hev 30 c# linq ienumerable predicate contains

我只需要澄清给定的集合包含一个元素.

我可以做到这一点,collection.Count(foo => foo.Bar == "Bar") > 0)但它会做不必要的工作 - 迭代整个集合,而我需要在第一次出现时停止.

但我想尝试使用Contains()谓词,例如foo => foo.Bar == "Bar".

目前IEnumerable<T>.Contains有两个签名:

  • IEnumerable<T>.Contains(T)

  • IEnumerable<T>.Contains(T, IEqualityComparer<T>)

所以我必须指定一些变量来检查:

var collection = new List<Foo>() { foo, bar };
collection.Contains(foo);
Run Code Online (Sandbox Code Playgroud)

或写我IEqualityComparer<Foo>将用于反对我的收藏的自定义:

class FooComparer : IEqualityComparer<Foo>
{
    public bool Equals(Foo f1, Foo f2)
    {
        return (f1.Bar == f2.Bar); // my predicate
    }

    public int GetHashCode(Foo f)
    {
        return f.GetHashCode();
    }   
}
Run Code Online (Sandbox Code Playgroud)

那么有没有其他方法可以使用谓词?

Mar*_*ell 61

.Any(predicate)
Run Code Online (Sandbox Code Playgroud)

听起来像你想要的; 返回bool,true一找到匹配就返回,否则false.还有:

.All(predicate)
Run Code Online (Sandbox Code Playgroud)

其行为方式类似,false一旦找到不匹配就返回,否则true.


sTo*_*rov 8

你可以用Any(predicate).它将返回true或false,具体取决于谓词是否存在于某个集合中.


Flo*_*chl 8

看一下IEnumerable<T>.Any扩展名.