0
votes

How do I pass a anon function in the parameter to be ran in a select statement?

    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);
        }
    } 

I get the error:

The type arguments for method 'Enumerable.Select(IEnumerable, Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly

What am I doing wrong?

I want to call it like this:

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

2 Answers

2
votes

The problem is with your tokenFunc it should be of type Func<TSource, TResult> and you are supplying Func<TResult>.

Naively, looking at how you are calling it, it should become:

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);
    }
} 

But this will, of course, fail, as you are trying to assign the result to IEnumerable<string> but are effectively returning IEnumerable<int>

To make it all work together you need to change things to Func<string, string> and return "0" or "1" instead of 0 or 1 in your call:

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);
    }
} 

And change the calling code to:

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

Because you need a Func taking string as input and returning your return type:

Func<string,int> tokenFunc