Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
  1. Instead of using a bunch of ifs to check the fieldname (sortBy), is there a cleaner way of doing the sorting
  2. Is sort aware of datatype?
like image 418
DotnetDude Avatar asked Oct 04 '22 22:10

DotnetDude


People also ask

How do I sort a list in Lambda?

The list. sort() method key parameter is set to lambda. The arguement x is the iterable element ( tuple ) to be sorted by the second element, the number. The lambda expression sorts the list by the second element of the tuple value and updates the original.

How would you sort the list in ascending order LINQ?

In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order. We don't need to add any ascending condition in the query statement.

How do you sort a list in C#?

Sort() Method Set -1. List<T>. Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.

Which is faster LINQ or Lambda?

There is no performance difference between LINQ queries and Lambda expressions.


2 Answers

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) );
like image 400
gls123 Avatar answered Oct 19 '22 18:10

gls123


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);
like image 75
Samuel Avatar answered Oct 19 '22 20:10

Samuel