How to implement method with expression parameter c#

后端 未结 3 1156
轮回少年
轮回少年 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:36

    You can turn a selector and value into a predicate using Expression.Equal:

    static IQueryable Search(
        this IQueryable source,
        Expression> selector,
        TValue value)
    {
        var predicate = Expression.Lambda>(
            Expression.Equal(
                selector.Body,
                Expression.Constant(value, typeof(TValue))
            ), selector.Parameters);
        return source.Where(predicate);
    }
    

    Then you just need to do something like:

    var result = database.SomeEntities.Search(x => x.SomeProp, "value");
    

    If you want to do it from the database, then that depends on what the database is; for example, with LINQ-to-SQL you could add an additional method:

    static IQueryable Search(
        this System.Data.Linq.DataContext database,
        Expression> selector,
        TValue value) where TSource : class
    {
        IQueryable source = database.GetTable();
        return Search(source, selector, value);
    }
    

    and use:

    var result = database.Search(x => x.SomeProp, "value");
    

    frankly I think it is clearer to use the database.SomeEntities version, though.

提交回复
热议问题