我们说我有这样的课程
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)
}
答案 0 :(得分:9)
如果您需要将列名称作为参数传递,那么您需要使用反射来进行比较。您可以执行以下操作:
modelList.OrderBy(a => a.GetType().GetProperty(columnName).GetValue(a, null));
当然你必须做适当的空检查等,我假设你可以照顾。
答案 1 :(得分:5)
我认为您正在寻找the overload of Sort() that takes a comparison function。
例如:
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);
});
}
答案 2 :(得分:1)
正确的方法是编写客户比较函数。
您需要知道的所有内容都可以在此处找到:http://msdn.microsoft.com/en-us/library/w56d4y5z%28v=vs.110%29.aspx
快走,如果它仍然无法工作,那就回来吧。
答案 3 :(得分:1)
您可以在此处从属性名称和排序方向创建动态表达式
答案 4 :(得分:1)
步骤1:实施IComparer接口
public class SortByName : IComparer<Customer>
{
public int Compare(Customer x, Customer y)
{
return x.Name.CompareTo(y.Name);
}
}
步骤2:传递实现IComparer接口的类的实例,作为Sort()方法的参数。
SortByName sortByName = new SortByName();
listModel.Sort(sortByName);