在Select中使用参数传递anon函数

时间:2016-02-18 23:20:19

标签: c# linq

如何在select语句中传递要运行的参数中的anon函数?

    public IEnumerable<string> Tokenize(Func<string> tokenFunc = null)
    {
        IEnumerable<string> tokens = Regex.Split(INPUT, @"(\d+|&|\||\(|\))").Where(x => string.IsNullOrEmpty(x) == false);
        if (tokenFunc != null)
        {
            tokens = tokens.Select(tokenFunc);
        }
    } 

我收到错误:

方法的类型参数&#39; Enumerable.Select(IEnumerable,Func)&#39;无法从使用中推断出来。尝试明确指定类型参数

我做错了什么?

我想这样称呼它:

MyViewObj.Tokenize( (x) => { if(x=='1') return 1; else return 0; });

2 个答案:

答案 0 :(得分:2)

问题在于您的tokenFunc应该是Func<TSource, TResult>类型,而您提供Func<TResult>

天真地看着你如何称呼它,它应该成为:

public IEnumerable<string> Tokenize(Func<string, int> tokenFunc = null)
{
    IEnumerable<string> tokens = Regex.Split(INPUT, @"(\d+|&|\||\(|\))").Where(x => string.IsNullOrEmpty(x) == false);
    if (tokenFunc != null)
    {
        tokens = tokens.Select(tokenFunc);
    }
} 

但是,这当然会失败,因为您尝试将结果分配给IEnumerable<string>,但实际上正在返回IEnumerable<int>

要使所有内容协同工作,您需要将内容更改为Func<string, string>并在通话中返回"0""1"而不是01

public IEnumerable<string> Tokenize(Func<string, string> tokenFunc = null)
{
    IEnumerable<string> tokens = Regex.Split(INPUT, @"(\d+|&|\||\(|\))").Where(x => string.IsNullOrEmpty(x) == false);
    if (tokenFunc != null)
    {
        tokens = tokens.Select(tokenFunc);
    }
} 

将调用代码更改为:

MyViewObj.Tokenize( (x) => { if(x=="1") return "1"; else return "0"; });

答案 1 :(得分:0)

因为您需要一个Func将字符串作为输入并返回您的返回类型:

Func<string,int> tokenFunc