我已经实施了书呆子晚餐的分页方法 - 效果很好。但我希望能够动态地按照certian字段进行排序。
我将如何实施此功能。这是我的代码?
控制器:
PaginatedList<Classifieds_Ads> pageOfClassifieds = new PaginatedList<Classifieds_Ads>(classifiedsRepositry.GetClassifiedsInCategory(category), paging, 20);
存储库:
return from classifieds in context.Classifieds_Ads.Include("User")
where (from catergory in context.Classifieds_Categories
where catergory.MVC_URL == MVC_Cat
select catergory).Contains(classifieds.Classifieds_Categories)
orderby classifieds.DatePosted descending
select classifieds;
正如您所看到的,我将orderby子句“硬编码”到我的存储库中。我只是不知道动态实现它的代码?
有人有什么想法吗?
谢谢,
答案 0 :(得分:2)
您可以使用OrderBy(Of TSource,TKey)-Extensionmethod并通过keySelector-parameter传递自定义函数。也许这个小例子可能会让你知道如何开始:
class A
{
public String Foo { get; set; }
public Int32 Bar { get; set; }
public override string ToString()
{
return Foo + ":" + Bar.ToString();
}
}
static void Main(string[] args)
{
var x = new List<A> { new A { Foo = "ABC", Bar = 100 }, new A() { Foo = "ZZZ", Bar = 0 } };
Func<A, String> order1 = (a) => a.Foo;
Func<A, Int32> order2 = (a) => a.Bar;
PrintQuery(x, order1);
Console.WriteLine();
PrintQuery(x, order2);
Console.ReadLine();
}
static void PrintQuery<T>(IEnumerable<A> query, Func<A, T> orderFunc)
{
foreach (var e in query.OrderBy(orderFunc))
Console.WriteLine(e);
}