结合多个谓词 [英] Combine Multiple Predicates
问题描述
有没有在C#.NET 2.0的任何方式!多个谓词结合?
Is there any way in c# .NET 2.0! to combine multiple Predicates?
让我们说我有下面的代码。
Let's say I have the following code.
List<string> names = new List<string>();
names.Add("Jacob");
names.Add("Emma");
names.Add("Michael");
names.Add("Isabella");
names.Add("Ethan");
names.Add("Emily");
List<string> filteredNames = names.FindAll(StartsWithE);
static bool StartsWithE(string s)
{
if (s.StartsWith("E"))
{
return true;
}
else
{
return false;
}
}
这给了我:
Emma
Ethan
Emily
所以这是很酷的东西,但我知道,希望能够使用多个谓词来过滤。
So this is pretty cool stuff, but I know want to be able to filter using multiple predicates.
所以我想能够说是这样的:
So I want to be able to say something like this:
List<string> filteredNames = names.FindAll(StartsWithE OR StartsWithI);
为了得到:
Emma
Isabella
Ethan
Emily
我怎样才能做到这一点?
目前,我只是过滤完整列表两次,结果事后的完美组合。但不幸的是这是一个相当inefficent,更重要的是我失去了原有的排列顺序,这是不是在我的情况可以接受的。
How can I achieve this? Currently I am just filtering the complete list twice and combining the results afterwards. But unfortunately this is quite inefficent and even more importantly I lose the original sort order, which is not acceptable in my situation.
我还需要能够遍历所有过滤器/谓词的号码可以有相当多的。
I also need to be able to iterate over any number of filters/predicates as there can be quite a lot.
同样它需要一个.NET 2.0解决方案,不幸的是我不能使用该框架的新版本
Again it needs to be a .NET 2.0 solution unfortunately I can't use a newer version of the framework
非常感谢
推荐答案
怎么样:
public static Predicate<T> Or<T>(params Predicate<T>[] predicates)
{
return delegate (T item)
{
foreach (Predicate<T> predicate in predicates)
{
if (predicate(item))
{
return true;
}
}
return false;
};
}
和完整性:
public static Predicate<T> And<T>(params Predicate<T>[] predicates)
{
return delegate (T item)
{
foreach (Predicate<T> predicate in predicates)
{
if (!predicate(item))
{
return false;
}
}
return true;
};
}
然后调用它:
Then call it with:
List<string> filteredNames = names.FindAll(Helpers.Or(StartsWithE, StartsWithI));
另一种方法是使用多播委托,然后用它们分割 GetInvocationList( )
,然后做同样的事情。然后,你可以这样做:
Another alternative would be to use multicast delegates and then split them using GetInvocationList()
, then do the same thing. Then you could do:
List<string> filteredNames = names.FindAll(Helpers.Or(StartsWithE+StartsWithI));
我不是,虽然后一种方式的一个巨大的风扇 - 那感觉就像一个有点滥用的多播。
I'm not a huge fan of the latter approach though - it feels like a bit of an abuse of multicasting.
这篇关于结合多个谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!