Bạn có thể bật một selector và giá trị vào một vị sử dụng 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);
}
Sau đó, bạn chỉ cần làm một cái gì đó như:
var result = database.SomeEntities.Search(x => x.SomeProp, "value");
Nếu bạn muốn làm điều đó từ cơ sở dữ liệu , thì điều đó tùy thuộc vào cơ sở dữ liệu là; ví dụ, với LINQ-to-SQL bạn có thể thêm một phương pháp bổ sung:
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);
}
và sử dụng:
var result = database.Search<SomeEntity, string>(x => x.SomeProp, "value");
thẳng thắn Tôi nghĩ rằng đó là rõ ràng hơn để sử dụng phiên bản database.SomeEntities
, mặc dù.
Nguồn
2013-05-08 09:19:31
bạn muốn tạo phương thức hoạt động tương tự như phương thức 'Tìm kiếm()', theo cách tổng quát? –
@Wim Ombelets yes – Nodir