开发者

How to structure a delegate that points to an extension method

开发者 https://www.devze.com 2023-01-13 12:25 出处:网络
I have a LINQ query, and I want to have a delegate that I can assign the \"OrderBy\" or \"开发者_StackOverflow中文版OrderByDescending\"methods to.The signature of the \"OrderBy\" extension method is:

I have a LINQ query, and I want to have a delegate that I can assign the "OrderBy" or "开发者_StackOverflow中文版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?


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;
    }
}


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);


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

精彩评论

暂无评论...
验证码 换一张
取 消