关于c#:将func从方法参数传递到LINQ方法(通用类型)

Passing func from method parameter into a LINQ method (generic types)

在方法的签名中,我指定一个Func,如下所示:

1
public void Method (Func<string, bool> func)

在LINQ中,哪种方法(来自IEnumerable)可以将Func从方法参数传递给LINQ查询?另一个问题是,我的func可以具有任何类型参数,因此IEnumerable / LINQ中的Method必须支持通用类型占位符。

我想写这样的东西:

1
2
3
4
5
6
7
// Get all elements of type T from the webpage (find is an object in an external API to look for elements in a page).

IEnumerable< T > images = find.GetAllByTagName< T >().All(func);

// Where func is a method parameter which is assigned at run time by the consumer of this API:

public void Test (Func<T, bool> func) { }

我怎样才能最好地做到这一点?我在.NET 3.5

谢谢


In LINQ, which method (from IEnumerable) will let me pass in a Func from the method parameter to the LINQ query?

LinqToObjects的扩展方法挂在静态System.Linq.Enumerable类上。

鉴于您的Func签名,您可能希望此Enumerable.Where的重载。

IEnumerable<T> Enumerable.Where<T>(this IEnumerable<T> source, Func<T, bool> filter)


将您的API签名更改为开放状态:

1
public void Method< T > (Predicate< T > func)

您的使用者将关闭类型T的通用签名,并提供适当的谓词。

使用LINQ的实际方法实现将使用Joel的前述Where()

编辑:将func更改为谓词

其他编辑:

我个人将返回一个IEnumerable,它表示您的结果集受传入谓词的约束:

1
2
3
4
public IEnumerable Method< T > (Predicate< T > func)
{
    return find.Where(func)
}

我正在假设您要做什么,请告诉我这是否是您的意图。


In LINQ, which method (from
IEnumerable) will let me pass in a
Func from the method parameter to the
LINQ query?

这个问题对我来说有点模糊。如果要查找仅返回Func指定的匹配项的过滤器算法,请使用.Where方法:

1
2
3
4
public void Method (Func<string, bool> func)
{
    return find.GetAllByTagName< T >().Where(func);
}

这能回答您的问题吗?如果不是,请说明您要做什么。