Combine Lambda Expressions

后端 未结 3 773
别那么骄傲
别那么骄傲 2020-12-06 02:31

I am looking for a way to combine two lambda expressions, without using an Expression.Invoke on either expression. I want to essentially build a new expression

3条回答
  •  忘掉有多难
    2020-12-06 03:15

    Update: the below answer generates an "Invoke" which EF does not support.

    I know this is an old thread, but I have the same need and I figured out a cleaner way to do it. Assuming that you can alter your "expression2" to user a generic lambda, you can inject one like this:

    class Program
    {
        private static Expression> GetValueFromFoo(Func getFoo)
        {
            return t => getFoo(t).Bar.Value;
        }
    
        static void Main()
        {
            Expression> getValueFromBar = GetValueFromFoo(m => m.SubModel.Foo);
    
            // test it worked
            var func = getValueFromBar.Compile();
            Model test = new Model
            {
                SubModel = new SubModel
                {
                    Foo = new Foo
                    {
                        Bar = new Bar { Value = "abc" }
                    }
                }
            };
            Console.WriteLine(func(test)); // "abc"
        }
    }
    

提交回复
热议问题