You can include the selector and value in the predicate using 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); }
Then you just need to do something like:
var result = database.SomeEntities.Search(x => x.SomeProp, "value");
If you want to do this from a database, it depends on what the database is; for example, with LINQ-to-SQL you can add an additional method:
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); }
and use:
var result = database.Search<SomeEntity, string>(x => x.SomeProp, "value");
frankly, I think itβs more understandable to use the version of database.SomeEntities .
source share