Sorting a list using Lambda/Linq to objects
I have the name of the "sort by property" in a string. I will need to use Lambda/Linq to sort the list of objects.
Ex:
public class Employee
{
public string FirstName {set; get;}
public string LastName {set; get;}
public DateTime DOB {set; get;}
}
public void Sort(ref List<Employee> list, string sortBy, string sortDirection)
{
//Example data:
//sortBy = "FirstName"
//sortDirection = "ASC" or "DESC"
if (sortBy == "FirstName")
{
list = list.OrderBy(x => x.FirstName).toList();
}
}
- Instead of using a bunch of ifs to check the fieldname (sortBy), is there a cleaner way of doing the sorting
- Is sort aware of datatype?
Solution 1:
This can be done as
list.Sort( (emp1,emp2)=>emp1.FirstName.CompareTo(emp2.FirstName) );
The .NET framework is casting the lambda (emp1,emp2)=>int
as a Comparer<Employee>.
This has the advantage of being strongly typed.
If you need the descending/reverse order invert the parameters.
list.Sort( (emp1,emp2)=>emp2.FirstName.CompareTo(emp1.FirstName) );
Solution 2:
One thing you could do is change Sort
so it makes better use of lambdas.
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);
}
Now you can specify the field to sort when calling the Sort
method.
Sort(ref employees, e => e.DOB, SortDirection.Descending);
Solution 3:
You could use Reflection to get the value of the property.
list = list.OrderBy( x => TypeHelper.GetPropertyValue( x, sortBy ) )
.ToList();
Where TypeHelper has a static method like:
public static class TypeHelper
{
public static object GetPropertyValue( object obj, string name )
{
return obj == null ? null : obj.GetType()
.GetProperty( name )
.GetValue( obj, null );
}
}
You might also want to look at Dynamic LINQ from the VS2008 Samples library. You could use the IEnumerable extension to cast the List as an IQueryable and then use the Dynamic link OrderBy extension.
list = list.AsQueryable().OrderBy( sortBy + " " + sortDirection );