Is there any way to pass the lambda expression as a variable or argument?

后端 未结 5 1241
-上瘾入骨i
-上瘾入骨i 2021-02-19 07:10

I need to pass the lambda query as a parameter, the followings code is sample and I am interesting to find an implement for it, there is samples: some thing like this:

5条回答
  •  后悔当初
    2021-02-19 07:57

    Check Func(Of T, TResult) Delegate (MSDN)

    using System;
    
    public class LambdaExpression
    {
       public static void Main()
       {
           Func convert = s => s.ToUpper();
    
           string name = "Dakota";
           Console.WriteLine(convert(name));   
       }
    }
    

    From MSDN

    The underlying type of a lambda expression is one of the generic Func delegates. This makes it possible to pass a lambda expression as a parameter without explicitly assigning it to a delegate. In particular, because many methods of types in the System.Linq namespace have Func(Of T, TResult) parameters, you can pass these methods a lambda expression without explicitly instantiating a Func(Of T, TResult) delegate.

    EDIT

    Possible solution for your case

    static void Main(string[] args) 
    {
        List numbers = new List { 10, 24, 9, 87, 193, 12, 7, 2, -45, -2, 9 };
        Func, IEnumerable> expr = n => n.Where(n1 => n1 > 6).OrderBy(n1 => n1 % 2 == 0).Select(n1 => n1);
        UseLambda(numbers, expr);
    }
    private static void UseLambda(List numbers, 
                                     Func, 
                                     IEnumerable> expr) 
    {
        var values = expr(numbers);
        foreach (var item in values) {
           Console.WriteLine(item);
        }
    }
    

提交回复
热议问题