views:

77

answers:

1

Hi,

I have implemented nerd dinner method of paging- which works great. But I want to be able to dynamically be able to order by certian fields.

How would I go about implementing this. Here is my code?

Controller:

 PaginatedList<Classifieds_Ads> pageOfClassifieds = new PaginatedList<Classifieds_Ads>(classifiedsRepositry.GetClassifiedsInCategory(category), paging, 20);

Repository:

    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;

As you can see I have the orderby clause "hard coded" into my repository. I just don't know the code to implement it dynamically?

Anybody have any ideas?

Thanks,

+1  A: 

You can use the OrderBy(Of TSource, TKey)-Extensionmethod and pass a custom Function via the keySelector-parameter. Maybe this little example may give you an idea how to start:

    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);
    }
dkson
Thank you very much this example was enough for me to come up with my own solution. Thanks very much.
Csharper