C# IEnumerable<;T>;。包含谓词
我只需要澄清,给定的集合包含一个元素 我可以通过C# IEnumerable<;T>;。包含谓词,c#,linq,ienumerable,contains,predicate,C#,Linq,Ienumerable,Contains,Predicate,我只需要澄清,给定的集合包含一个元素 我可以通过collection.Count(foo=>foo.Bar==“Bar”)>0)来实现这一点,但它将完成不必要的工作—迭代整个集合,而我需要在第一次出现时停止 但是我想尝试使用带有谓词的Contains(),例如foo=>foo.Bar==“Bar” 当前IEnumerable.Contains有两个签名: IEnumerable.Contains(T) IEnumerable.Contains(T,IEqualityComparer) 因此,
collection.Count(foo=>foo.Bar==“Bar”)>0)
来实现这一点,但它将完成不必要的工作—迭代整个集合,而我需要在第一次出现时停止
但是我想尝试使用带有谓词的Contains()
,例如foo=>foo.Bar==“Bar”
当前IEnumerable.Contains
有两个签名:
IEnumerable.Contains(T)
IEnumerable.Contains(T,IEqualityComparer)
var collection = new List<Foo>() { foo, bar };
collection.Contains(foo);
var collection=newlist(){foo,bar};
集合。包含(foo);
或者编写我的自定义IEqualityComparer
,用于我的收藏:
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();
}
}
class FooComparer:IEqualityComparer
{
公共布尔等于(Foo f1,Foo f2)
{
return(f1.Bar==f2.Bar);//我的谓词
}
public int GetHashCode(Foo f)
{
返回f.GetHashCode();
}
}
那么还有其他方法可以使用谓词吗
.Any(predicate)
听起来像你想要的;返回bool
,找到匹配项后立即返回true
,否则返回false
。还有:
.All(predicate)
其行为方式类似,一旦发现不匹配项就返回false
,否则true
您可以使用任何(谓词)
。
它将返回true或false,具体取决于谓词是否存在于某个集合中。请查看
IEnumerable.Any
扩展名