简体   繁体   English

C#如何按任何属性对对象列表进行排序

[英]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' 此类设置为列表视图的源,并且以下函数中传递的sortExpression参数是属性名称,其排序顺序为'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? 实现此目的的唯一方法是为每个属性编写一个Comparator,或者LINQ中的某些操作可以轻松完成此操作?

To do what you need, you can use LINQ Dynamic Query Library which allows you to pass string to your OrderBy . 要执行所需的操作,可以使用LINQ动态查询库,该库允许您将string传递给OrderBy

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

Here full tutorial 这里完整的教程

https://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library 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 另一个解决方案是使该方法接受Expression

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); list.OrderBy(x => x.property);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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