自定义列表排序

根据排序表达式对列表跟进动态字段进行排序。

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> list, string sortExpression)
{
sortExpression += "";
string[] parts = sortExpression.Split(' ');
bool descending = false;
string property = "";

if (parts.Length > 0 && parts[0] != "")
{
property = parts[0];

if (parts.Length > 1)
{
descending = parts[1].ToLower().Contains("esc");
}

PropertyInfo prop = typeof(T).GetProperty(property);

if (prop == null)
{
throw new Exception("No property '" + property + "' in + " + typeof(T).Name + "'");
}

if (descending)
return list.OrderByDescending(x => prop.GetValue(x, null));
else
return list.OrderBy(x => prop.GetValue(x, null));
}

return list;
}

示例:

1
2
3
4
5
6
7
8
class Customer
{
public string Name{get;set;}
}

var list = new List<Customer>();

list.OrderBy("Name desc");
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×