如何使用表达式参数c#实现方法

Nod*_*dir 6 .net c# linq

我想创建一个这样的方法:

var result = database.Search<EntityType>(x=>x.Name, "Entity Name field value");
result = database.Search<EntityType>(x=>x.Id, "Entity Id field value");
result = database.Search<EntityType2>(x=>x.Id, "Entity2 Id field value");
result = database.Search<EntityTypeAny>(x=>x.FieldAny, "EntityAny FieldAny value");
Run Code Online (Sandbox Code Playgroud)

我该如何实现这个方法?

Mar*_*ell 11

您可以使用以下命令将选择器和值转换为谓词Expression.Equal:

static IQueryable<TSource> Search<TSource, TValue>(
    this IQueryable<TSource> source,
    Expression<Func<TSource,TValue>> selector,
    TValue value)
{
    var predicate = Expression.Lambda<Func<TSource,bool>>(
        Expression.Equal(
            selector.Body,
            Expression.Constant(value, typeof(TValue))
        ), selector.Parameters);
    return source.Where(predicate);
}
Run Code Online (Sandbox Code Playgroud)

然后你只需要做一些事情:

var result = database.SomeEntities.Search(x => x.SomeProp, "value");
Run Code Online (Sandbox Code Playgroud)

如果你想从数据库中做到这一点,那么这取决于数据库什么; 例如,使用LINQ-to-SQL,您可以添加其他方法:

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

并使用:

var result = database.Search<SomeEntity, string>(x => x.SomeProp, "value");
Run Code Online (Sandbox Code Playgroud)

坦率地说,我认为使用该database.SomeEntities版本更为清晰.