-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinqExtensions.cs
66 lines (47 loc) · 2.4 KB
/
LinqExtensions.cs
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
public static class LinqExtensions
{
public static IOrderedEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> source, string propertyName)
{
PropertyInfo prop = typeof(TSource).GetProperty(propertyName);
if (prop == null)
{
throw new Exception("No property '" + propertyName + "' in + " + typeof(TSource).Name + "'");
}
return source.OrderBy(x => prop.GetValue(x, null));
}
public static IOrderedEnumerable<TSource> OrderByDescending<TSource>(this IEnumerable<TSource> source, string propertyName)
{
PropertyInfo prop = typeof(TSource).GetProperty(propertyName);
if (prop == null)
{
throw new Exception("No property '" + propertyName + "' in + " + typeof(TSource).Name + "'");
}
return source.OrderByDescending(x => prop.GetValue(x, null));
}
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName)
{
return (IOrderedQueryable<T>)OrderBy((IQueryable)source, propertyName);
}
public static IQueryable OrderBy(this IQueryable source, string propertyName)
{
var x = Expression.Parameter(source.ElementType, "x");
var selector = Expression.Lambda(Expression.PropertyOrField(x, propertyName), x);
return source.Provider.CreateQuery(
Expression.Call(typeof(Queryable), "OrderBy", new Type[] { source.ElementType, selector.Body.Type },
source.Expression, selector
));
}
public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string propertyName)
{
return (IOrderedQueryable<T>)OrderByDescending((IQueryable)source, propertyName);
}
public static IQueryable OrderByDescending(this IQueryable source, string propertyName)
{
var x = Expression.Parameter(source.ElementType, "x");
var selector = Expression.Lambda(Expression.PropertyOrField(x, propertyName), x);
return source.Provider.CreateQuery(
Expression.Call(typeof(Queryable), "OrderByDescending", new Type[] { source.ElementType, selector.Body.Type },
source.Expression, selector
));
}
}