01.
Imports
System.Collections.Generic
02.
Imports
System.Linq
03.
Imports
System.Reflection
04.
Imports
System.Linq.Expressions
05.
06.
Public
Module
IEnumerableHelper
07.
08.
Sub
New
()
09.
End
Sub
10.
11.
Private
orderBy_
As
MethodInfo =
GetType
(Enumerable).GetMethods(BindingFlags.[
Static
]
Or
BindingFlags.[
Public
]) _
12.
.Where(
Function
(x) x.Name =
"OrderBy"
AndAlso
x.GetParameters().Length = 2).First()
13.
14.
15.
16.
17.
18.
19.
20.
21.
<System.Runtime.CompilerServices.Extension()> _
22.
Public
Function
OrderBy(Of TSource)(source
As
IEnumerable(Of TSource), propertyName
As
String
)
As
IEnumerable(Of TSource)
23.
Dim
pi =
GetType
(TSource).GetProperty(propertyName, BindingFlags.[
Public
]
Or
BindingFlags.FlattenHierarchy
Or
BindingFlags.Instance)
24.
Dim
selectorParam = Expression.Parameter(
GetType
(TSource),
"keySelector"
)
25.
Dim
sourceParam = Expression.Parameter(
GetType
(IEnumerable(Of TSource)),
"source"
)
26.
Return
Expression.Lambda(Of Func(Of IEnumerable(Of TSource),
27.
IOrderedEnumerable(Of TSource)))(Expression.[
Call
](orderBy_.MakeGenericMethod(
GetType
(TSource), pi.PropertyType),
28.
sourceParam, Expression.Lambda(
GetType
(Func(Of ,)).MakeGenericType(
GetType
(TSource), pi.PropertyType),
29.
Expression.[
Property
](selectorParam, pi), selectorParam)), sourceParam).Compile()(source)
30.
End
Function
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
<System.Runtime.CompilerServices.Extension()> _
41.
Public
Function
OrderBy(Of TSource)(source
As
IEnumerable(Of TSource), propertyName
As
String
, ascending
As
Boolean
)
As
IEnumerable(Of TSource)
42.
Return
If
(ascending, source.OrderBy(propertyName), source.OrderBy(propertyName).Reverse())
43.
End
Function
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
<System.Runtime.CompilerServices.Extension> _
55.
Public
Function
DistinctBy(Of T, TKey)(items
As
IEnumerable(Of T), [property]
As
Func(Of T, TKey))
As
IEnumerable(Of T)
56.
Return
items.GroupBy([property]).[
Select
](
Function
(x) x.First())
57.
End
Function
58.
End
Module