IEnumerable的< T>。载有谓语 [英] IEnumerable<T>.Contains with predicate
问题描述
我只需要澄清,给出集合包含的元素。
我能做到这一点通过 collection.Count(富=> foo.Bar ==酒吧)> 0)
,但它会做不必要的工作 - 遍历整个集合,而我需要停止在第一次出现
但我想尝试使用包含()
有一个谓语,如富=> 。foo.Bar ==栏
目前的IEnumerable< T>。载
有两个特征:
-
的IEnumerable< T>。载有(T)
-
的IEnumerable< T>。载有(T,的IEqualityComparer< T>)
所以,我必须指定一些变量来检查:
VAR收集=新的List<富>(){富,巴};
collection.Contains(富);
或写我自定义的的IEqualityComparer<富>
这将打击我的收藏中:
类FooComparer:&的IEqualityComparer LT;富>
{
公共布尔等于(富F1,F2富)
{
回报率(f1.Bar == f2.Bar); //我的谓语
}
公众诠释的GetHashCode(富F)
{
返回f.GetHashCode();
}
}
那么,还有没有其他的方法来使用谓词<? / p>
。任何(谓语)
听起来像是你想要的东西;返回布尔
,返回真正
只要找到一个匹配,否则假
。此外还有:
。所有(谓语)
其行为以类似的方式,返回假
只要非匹配,否则真正
。
I need just to clarify that given collection contains an element.
I can do that via collection.Count(foo => foo.Bar == "Bar") > 0)
but it will do the unnecessary job - iterate the whole collection while I need to stop on the first occurrence.
But I want to try to use Contains()
with a predicate, e.g. foo => foo.Bar == "Bar"
.
Currently IEnumerable<T>.Contains
has two signatures:
IEnumerable<T>.Contains(T)
IEnumerable<T>.Contains(T, IEqualityComparer<T>)
So I have to specify some variable to check:
var collection = new List<Foo>() { foo, bar };
collection.Contains(foo);
or write my custom IEqualityComparer<Foo>
which will be used against my collection:
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();
}
}
So are there any other methods to use predicate?
.Any(predicate)
sounds like what you want; returns bool
, returning true
as soon as a match is found, else false
. There is also:
.All(predicate)
which behaves in a similar way, returning false
as soon as a non-match is found, else true
.
这篇关于IEnumerable的< T>。载有谓语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!