2010-07-23 64 views
0

我已经实现了寻呼的书呆子晚餐方法 - 这非常棒。但我希望能够动态地按照certian字段进行排序。Nedd Dinner pagginated list - 如何添加linq orderby子句dynamicaly?任何人?

我将如何去实现这一点。这是我的代码?

控制器:

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; 

正如你可以看到我有排序依据条款 “硬编码” 到我的仓库。我只是不知道动态实现它的代码?

任何人有什么想法?

感谢,

+0

如果你告诉我你的函数的分类类型和方法签名,我可以给你一个更好的例子。 – sloth 2010-07-23 11:48:47

回答

2

您可以使用OrderBy(中TSource,TKEY的)-Extensionmethod,并通过使用KeySelector参数传递一个自定义函数。也许这个小例子可以让你知道如何开始:

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); 
    } 
+0

非常感谢你这个例子足以让我想出我自己的解决方案。非常感谢。 – SimonGates 2010-07-23 14:06:19