按列名称字符串对列表进行排序

2024-04-02

假设我有一堂这样的课

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

我有一个类型模型列表

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

如何按列名和排序方向对 modelList 进行排序?

我尝试过的方法:

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

我想你正在寻找采用比较函数的 Sort() 重载 http://msdn.microsoft.com/en-us/library/tfakywbh%28v=vs.110%29.aspx .

例如:

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

OrderBy 具有类似的灵活性,但返回一个已排序的新序列,而不是修改原始列表。所以,你可以这样做:

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

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

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);
    });
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按列名称字符串对列表进行排序 的相关文章

随机推荐