tags:

views:

57

answers:

3

I have a LINQ query, and I want to have a delegate that I can assign the "OrderBy" or "OrderByDescending" methods to. The signature of the "OrderBy" extension method is:

public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector)

Can anyone show me what the delegate would look like?

+2  A: 
public delegate IOrderedEnumerable<TSource> OrderByFunc<TSource, TKey>(
    IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector);

Usage:

public OrderByFunc<TSource, TKey> GetOrderByFunc<TSource, TKey>(bool descending)
{
    if (descending)
    {
        return Enumerable.OrderByDescending;
    }
    else
    {
        return Enumerable.OrderBy;
    }
}
dtb
So you'd use this as: `db.Contacts.GetOrderByFunc(false)(c=>c.LastName);` ?
James Curran
@James Curran: Yes, that's one possible usage. But `GetOrderByFunc` is just an example. I don't know what the OP intends to do with the delegate.
dtb
+1  A: 

You can either ignore the "this" parameter when structuring your delegate, or you can construct the delegate from an instance that the delegate hung off of.

delegate IOrderedEnumerable<TSource> OrderDelegate<TSource,TKey>
         (IEnumerable<TSource> source, 
          Func<TSource, TKey> keySelector);
Philip Rieck
A: 

You need to define a function which takes as a parameter an object of the type of the table, and return the value from the object that you want to sort by:

Say you have a Table of People, each item is a Person, and you want to sort by LastName:

public static string ByLastName(Person p)
{
     return p.LastName;
}


 db.People.Where(p=>p.age > 25).OrderBy(ByLastName);
James Curran