使用泛型类型C#拉姆达查询 [英] C# lambda query using generic type
问题描述
我有三个类,它们都有一个属性的日期。我想编写一个通用类返回所有记录一个日期。
现在的问题是:我怎么能使用通用类型T编写lambda表达式
I have three classes, they all have a property Date. I would like to write a generic class to return all the records for one date. Now the problem is: how can I write the lambda expression using generic type T?
代码简单的是如下(我会不编译,因为? r.Date不会工作,但它的,我想才达到的效果)
The code simple is as below (i'll not compile, because "r.Date" would not working,but it's the effect that I'd like to achive)
Class GenericService<T>: IGenericService<T> where T:class
{
...
readonly IGenericRepository<T> _genericRepository;
public IEnumerable<T> GetRecordList(DateTime date)
{
var query=_genericRepository.FindBy(r=>r.Date=date);
}
感谢您对您的帮助!
问候,
利昂娜
Regards, Léona
推荐答案
另一个选择是建立一个表达
动态。如果你不想或者不能在 IDATE
接口添加到模型对象,如果 FindBy $ C这可能是有用$ C>需要一个
表达式来; Func键< T,BOOL>>
(例如,将其转换为的IQueryable< T>。凡(.. 。)
内部进行的EntityFramework或相似的。
Another option is to build an Expression
dynamically. This can be useful if you don't want to or can't add an IDate
interface to the model objects, and if FindBy
needs an Expression<Func<T, bool>>
(for example, it translates to IQueryable<T>.Where(...)
internally for EntityFramework or similar.
像@ JonB的回答,这没有任何编译时的安全,确保 T
有一个日期
属性或字段,它只会在运行时失败。
Like @JonB's answer, this has no compile-time safety to ensure that T
has a Date
property or field. It will only fail at runtime.
public IEnumerable<T> GetRecordList(DateTime date)
{
var parameterExpression = Expression.Parameter(typeof(T), "object");
var propertyOrFieldExpression = Expression.PropertyOrField(parameterExpression, "Date");
var equalityExpression = Expression.Equal(propertyOrFieldExpression, Expression.Constant(date, typeof(DateTime)));
var lambdaExpression = Expression.Lambda<Func<T, bool>>(equalityExpression, parameterExpression);
var query = _genericRepository.FindBy(lambdaExpression);
return query;
}
这篇关于使用泛型类型C#拉姆达查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!