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

后端 未结 5 1236
-上瘾入骨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 08:05

    public void UseLambda(IEnumerable source, Expression, IEnumerable>> expr)
    {
        var items = expr.Compile();
    
        foreach (var item in items.Invoke(source))
        {
            Console.WriteLine(item.ToString());
        }
    }
    
    
    public void Main()
    {
        Expression, IEnumerable>> expr = s => s.Where(n => n > 6).OrderBy(n => n % 2 == 0).Select(n => n);
        var list = new List { 10, 24, 9, 87, 193, 12, 7, 2, -45, -2, 9 };
    
        UseLambda(list, expr);
    }
    

提交回复
热议问题