How to implement method with expression parameter c#

后端 未结 3 1149
轮回少年
轮回少年 2021-02-06 12:29

I want to create a method like this:

var result = database.Search(x=>x.Name, \"Entity Name field value\");
result = database.Search

        
3条回答
  •  逝去的感伤
    2021-02-06 12:51

    I can only think of this (with 2 generic arguments)

        public static IEnumerable Search(
            Expression> expression,
            TValue value
        )
        {
            return new List();
        }
    

    usage

    var result = Search(x => x.Id, 1);
    var result2 = Search(x => x.Name, "The name");
    

    you can replace TValue with object to avoid the second generic argument, but I would stick with this.

    Btw. this works great in conjunction with this little helper

    public static class ExpressionHelpers
    {
        public static string MemberName(this Expression> expression)
        {
            var memberExpression = expression.Body as MemberExpression;
            if (memberExpression == null)
                throw new InvalidOperationException("Expression must be a member expression");
    
            return memberExpression.Member.Name;
        }
    }
    

    Now you can get the Name of the Property (Id oder Name) in this example by calling

    var name = expression.MemberName();
    

提交回复
热议问题