帮助通用LINQ OrderBy Lambda表达式 [英] Help With Generic LINQ OrderBy Lambda Expression
问题描述
这是我的方法:
公开ICollection< T>< T> FindAll< T>(表达式< Func< T,bool>>谓词,表达< Func< T,int>> orderingKey)其中T:Post
{
return repository
.Find ()
.Where(predicate)
.OfType< T>()
.OrderBy(orderingKey)
.ToPagedList();
}
如果我这样做,排序工作:
FindAll(p => p.PostName ==Foo,p => p.PostId);
但不要,如果我想这样做:
FindAll(p => p.PostName ==Foo,p => p.DateModified);
它当然不起作用,因为我已经将表达式声明为 T,int
,而上述表达式的类型为 T,DateTime
我是否声明它,所以我可以OrderBy 我的实体(Post)的任何属性?
这是LINQ-Entities(实体框架4.0)。
Queryable.OrderBy
使用以下类型的键选择器:
表达< Func< TSource,TKey>的KeySelector>
如果将orderingKey更改为此类型的表达式,那么它将工作。您还需要添加另一个类型参数。
public ICollection< T> FindAll< T,TKey>(
表达式< Func< T,bool>>谓词,
表达式< Func< T,TKey>" orderKey
)其中T:Post
Trying to get an OrderBy on an IQueryable to work, not having much luck.
Here's my method:
public ICollection<T> FindAll<T>(Expression<Func<T,bool>> predicate, Expression<Func<T,int>> orderingKey) where T : Post
{
return repository
.Find()
.Where(predicate)
.OfType<T>()
.OrderBy(orderingKey)
.ToPagedList();
}
The ordering works if i do this:
FindAll(p => p.PostName == "Foo", p => p.PostId);
But not if i want to do this:
FindAll(p => p.PostName == "Foo", p => p.DateModified);
It doesn't work of course, because i have declared the Expression as T,int
, whereas the above expression is of type T,DateTime
How do i declare it so i can OrderBy any property of my entity (Post)?
This is LINQ-Entities (Entity Framework 4.0).
Queryable.OrderBy
takes a key selector with the following type:
Expression<Func<TSource, TKey> keySelector>
If you change orderingKey to an expression of this type then it will work. You will also need to add another type parameter.
public ICollection<T> FindAll<T, TKey>(
Expression<Func<T, bool>> predicate,
Expression<Func<T, TKey>> orderingKey
) where T : Post
这篇关于帮助通用LINQ OrderBy Lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!