Home > Enterprise >  How to combine multiple Func<T,Tresult> dynamically in a for loop in C#
How to combine multiple Func<T,Tresult> dynamically in a for loop in C#

Time:10-01

I have a function that returns Func<T,TResult>. I want to return multiple funcs in a single func with || of one another.

Below func is just sample but my actual code contains multiple lines of code snippet in func. In which I have to check for each value of comma separated string. Like below function there are multiple functions which returns Func<string, bool>. And all these func will combine as && for further use

public static Func<string, bool> GetData(string request)
{
    var data = request.Split(',');
    //This func is just sample but my actual code contains multiple lines of code snippet in func. In which I have to use each value of comma separated string.
    Func<string, bool> selector = str => str.ToUpper() == data[0] || str => str.ToLower() == data[0] ;
    
    for(int i = i; i < data.Length; i  )
    {
        Func<string, bool> selector1 = str => str.ToUpper() == data[i]  || str => str.ToLower() == data[i] ;
        
        // something like this func || func1 || func2 || func3... and so on
        selector = selector || selector1;
    }
    
    return selector;
}

CodePudding user response:

I don't think you need multiple Funcs. Just use LINQ's Any function

public static Func<string, bool> GetData(string request)
{
    var data = request.Split(',');
    Func<string, bool> selector = str =>
        data.Any(d => d.Equals(str, StringComparison.OrdinalIgnoreCase));
    
    return selector;
}

Alternatively you can use Contains

    Func<string, bool> selector = str =>
        data.Contains(str, StringComparer.OrdinalIgnoreCase);

Note: OrdinalIgnoreCase is more efficient than calling ToUpper each time

CodePudding user response:

This problem you can solve easier:

public static Func<string, bool> GetData(string request)
{
  return str => request.Split(',').contains(str.ToUpper());
}

CodePudding user response:

Assuming you do need to use a list of Funcs, you can still combine them using LINQ

public static Func<string, bool> GetData(string request)
{
    var data = request.Split(',');
    var selectors = data.Select(d =>
        new Func<string, bool>(str => str.ToUpper() == d || str.ToLower() == d))  // would never use such code, but just your example
        .ToList();  // this is your list of selectors
    
    return str => selectors.Any(sel => sel(str));
}
  • Related