Można włączyć selektora i wartość w predykatem użyciu 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);
}
Wtedy po prostu trzeba zrobić coś takiego:
var result = database.SomeEntities.Search(x => x.SomeProp, "value");
Jeśli chcesz to zrobić z bazy danych , zależy to od bazy danych :; na przykład, z LINQ-SQL można dodać dodatkową metodę:
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);
}
i zastosowanie:
var result = database.Search<SomeEntity, string>(x => x.SomeProp, "value");
szczerze myślę, że jest jaśniejsza użyć wersji database.SomeEntities
, choć.
chcesz utworzyć metodę, która działa podobnie do metody 'Search()' w sposób ogólny? –
@Wim Ombelets yes – Nodir