0

I want to do the same as explained here: Sorting a list using Lambda/Linq to objects

that is:

public enum SortDirection { Ascending, Descending }
public void Sort<TKey>(ref List<Employee> list,
                   Func<Employee, TKey> sorter, SortDirection direction)
{
     if (direction == SortDirection.Ascending)
         list = list.OrderBy(sorter);
     else
         list = list.OrderByDescending(sorter);
}

to call it he said to do:

Sort(ref employees, e => e.DOB, SortDirection.Descending);

but I do not understand what TKey is refering to and as I can see in the call it is missed the generic TKey.

Could you explain me what is TKey and how to use it?

I suppose I can use another name for the method, it is not necessary to be Sort, right?

thanks!

Community
  • 1
  • 1
Ralph
  • 7,746
  • 14
  • 84
  • 190
  • 1
    Your code will not work. You will have to change it to: ` list = list.OrderBy(sorter).ToList();`. ` – Steven May 16 '13 at 10:06

1 Answers1

3

You sort by the key which is of type TKey and must implement IComparable<TKey>. For instance:

// key: Firstname
// TKey: string (which is IComparable<String>
list.OrderBy(person => person.Firstname);

The above code sorts by firstname, which is what you define using the sorter. And yes, you can give your method any name you like. It does not have to be named Sort.

Improvement Suggestion (indirectly related to the question)

instead of changing list and passing it as a reference I'd suggest you to consider the following implementation:

public IOrderedEnumerable<Employee> Sort<TKey>(IEnumerable<Employee> list, Func<Employee, TKey> sorter, SortDirection direction);
{
    IOrderedEnumerable<Employee> result;
    if (direction == SortDirection.Ascending)
        result = list.OrderBy(sorter);
    else
        result = list.OrderByDescending(sorter);
    return result;
}

You could then return a new ordered enumerable of Employee objects instead of changing the old one and use any enumerable instead of List object only. This gives you more flexibility and is closer to the LINQ implementation which people tend to be used to.

Matthias Meid
  • 12,080
  • 6
  • 41
  • 73