C#/LINQ: How to define generically a keySelector for a templated class before calling OrderBy

Posted by PierrOz on Stack Overflow See other posts from Stack Overflow or by PierrOz
Published on 2010-06-08T10:09:00Z Indexed on 2010/06/08 10:12 UTC
Read the original article Hit count: 296

Filed under:
|
|

Hi Folks,

I have the following class defined in C#

class myClass<T,U>
{
    public T PropertyOne { get; set; }
    public U PropertyTwo { get; set; }
}

I need to write a function that reorder a list of myClass objects and takes two other parameters which define how I do this reorder: does my reordering depend on PropertyOne or PropertyTwo and is it ascending or descending. Let's say this two parameters are boolean. With my current knowledge in LINQ, I would write:

public IList<myClass<T,U>> ReOrder(IList<myClass<T,U>> myList, bool usePropertyOne, bool ascending)
{
    if (usePropertyOne)
    {
        if (ascending)
        {
            return myList.OrderBy(o => o.PropertyOne).ToList();
        }
        else
        {
            return myList.OrderByDescending(o => o.PropertyOne).ToList();
        }
    }
    else
    {
        if (ascending)
        {
            return myList.OrderBy(o => o.PropertyTwo).ToList();
        }
        else
        {
            return myList.OrderByDescending(o => o.PropertyTwo).ToList();
        }
    }
}

What could be a more efficient/elegant way to do that ? How can I declare the Func,TResult> keySelector object to reuse when I call either OrderBy or OrderByDescending? I'm interesting in the answer since in my real life, I can have more than two properties.

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ