按列名字符串对列表进行排序 [英] Sort a list by column name string

查看:114
本文介绍了按列名字符串对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的班级

Let's say I have a class like this

public class model
{
    public int id{get;set;}
    public string name{get;set;}
    public string department{get;set;}
}

我有一个型号列表

List<model> modelList = List<model>();

如何通过其列名和排序方向对modelList进行排序?

How Can I sort the modelList by its column name with sort direction?

我尝试过的方法:

public List<model> sortModelList(string columnName, SortDirection direction)
{
   //Method 1:
   //The below code was unable to sort by column and unable to set the sort direction
   return modelList.Sort();

   //Method 2:
   //The below code was unable to sort by the columnName parameter and unable to set the sort direction
   return modelList.OrderBy(a=>a.name)

  //What I can do in order to sort the list by "columnName" parameter and set the sort direction? (Ascending / Descending)
}

推荐答案

我认为您正在寻找例如:

modelList.Sort((m1, m2) => string.Compare(m1.name, m2.name));
// descending
modelList.Sort((m1, m2) => -string.Compare(m1.name, m2.name));

OrderBy具有类似的灵活性,但返回的是排序后的新序列,而不是修改原始列表.因此,您可以这样做:

OrderBy has similar flexibility, but returns a new sequence which is sorted rather than modifying the original list. So, you could do:

var newList = modelList.OrderBy(m => m.name).ToList();
// descending
var newList = modelList.OrderByDescending(m => m.name).ToList();

要指定要动态排序的属性,请考虑以下代码:

To specify the property to be sorted by dynamically, consider the following code:

public void SortList<T>(List<T> list, string columnName, SortDirection direction)
{
    var property = typeof(T).GetProperty(columnName);
    var multiplier = direction == SortDirection.Descending ? -1 : 1;
    list.Sort((t1, t2) => {
        var col1 = property.GetValue(t1);
        var col2 = property.GetValue(t2);
        return multiplier * Comparer<object>.Default.Compare(col1, col2);
    });
}

这篇关于按列名字符串对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆