0
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?

  • 'IntField ASC' 'IntField DESC'? How does that work? – spender May 25 '18 at 12:16
  • That code doesn't even compile. – TJ Wolschon May 25 '18 at 12:17
  • You can construct expression on the fly for any property. – Antonín Lejsek May 25 '18 at 12:17
  • 1
    I imagine you're looking for something like `list.OrderBy(x=>x.IntField).ThenByDescending(x=>x.StringField)`, but your question is so poor, it's hard to guess what you want. – spender May 25 '18 at 12:18
  • Check this out: https://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object?rq=1 – Alvin May 25 '18 at 12:21
  • Possible duplicate of [How to Sort a List by a property in the object](https://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object) – Sinatr May 25 '18 at 12:23
  • @Sinatr No it is not duplicate: read last line "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?" I think, he already knows this solution but want better solution (he might want reflection) – Amit May 25 '18 at 12:28
  • You want dynamic LINQ. The answer you're looking for is here: https://stackoverflow.com/a/233505/3294832 – Ric .Net May 25 '18 at 12:29

2 Answers2

3

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);
}
Nashmár
  • 364
  • 1
  • 4
  • 20
Hany Habib
  • 1,249
  • 1
  • 10
  • 18
-2

Somthing like:

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

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

DannyP
  • 25
  • 5