简体   繁体   中英

C# How to sort a list of objects by any property

public class SortExample
{
  public int IntField {get; set;}

  public string StringField {get; set;}

  public DateTime DateField {get; set;}
}

This class is set as a source for a listview and the sortExpression param passed in function below is property name with sort order 'IntField ASC' 'IntField DESC' 'StringField ASC' 'StringField DESC'

public void SortExampleMethod(string sortExpression)
{
   List<SortExample> list = new  List<SortExample>();
   list.OrderBy(sortExpression);
}

Is the only way to implement this is to write a Comparator for every property or something in LINQ allows this to be done easily?

To do what you need, you can use LINQ Dynamic Query Library which allows you to pass string to your OrderBy .

ex: var result = list.OrderBy("intField asc");

Here full tutorial

https://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library

Another Solution is to make the method accepts Expression class

public void sort(Expression<Func<TEntity, S>> orderByExpression, bool ascending)
{

List<SortExample> list = new  List<SortExample>();
if(ascending)
{
   list.OrderBy(orderByExpression);
}
else
   list.OrderByDescneding(orderByExpression);
}

Somthing like:

list.OrderBy(x => x.property);

https://msdn.microsoft.com/en-us/library/bb534966.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM