自定义列表排序

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

源代码:

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

通过IQueryable创建List泛型集合的异步方法

通过System.Collections.Generic.IQueryable创建System.Collections.Generic.List集合的异步方法

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ReflectionIT.Linq {

static class Utils {

/// <summary>
/// 通过System.Collections.Generic.IQueryable<T>.创建System.Collections.Generic.List<T>的异步方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static Task<List<T>> ToListAsync<T>(this IQueryable<T> list) {
return Task.Run(() => list.ToList());
}

}
}

C#扩展方法:获取枚举Enum的description内容

通过枚举的名称获取分配的Description内容

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

public static class EnumHelper<T>
{
public static string GetEnumDescription(string value)
{
Type type = typeof(T);
var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();

if (name == null)
{
return string.Empty;
}
var field = type.GetField(name);
var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
}
}

示例

1
2
3
4
5
6
7
8
9
10
11
public enum GradeEnum
{
[Description("Passed")]
Pass,
[Description("Failed")]
Failed,
[Description("Promoted")]
Promoted
}

string description = EnumHelper<GradeEnum>.GetEnumDescription("pass");
Your browser is out-of-date!

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

×