Skip to content

Instantly share code, notes, and snippets.

@nikyodo85
Last active October 2, 2018 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikyodo85/202fc2d417d9eb030d30896ccc862b7d to your computer and use it in GitHub Desktop.
Save nikyodo85/202fc2d417d9eb030d30896ccc862b7d to your computer and use it in GitHub Desktop.
VB.NET extension method to sort IEnumerable of entities from Entity Framework by specifying either property name or column name (through column attribute). It is updated to support multiple columns and remove case sensitivity. For example: list.SortBy("propertyName, columeAttributeName DESC")
Imports System.ComponentModel.DataAnnotations.Schema
Imports System.Reflection
Imports System.Runtime.CompilerServices
Public Module IEnumerableExtensions
<Extension>
Public Function SortBy(Of T)(list As IEnumerable(Of T), sortByParams As String) As IEnumerable(Of T)
If String.IsNullOrWhiteSpace(sortByParams) Then
Return list
End If
Dim properties = GetType(T).GetProperties()
Dim sortingList As IOrderedEnumerable(Of T) = Nothing
Dim sortByParamArray = sortByParams.Split(",")
For i = 0 To sortByParamArray.Count - 1
Dim sortByParam = sortByParamArray(i).Trim()
Dim propertyToBeSorted As PropertyInfo = Nothing
Dim propertyToBeSortedName As String = sortByParam
Dim isDescending As Boolean
If sortByParam.EndsWith(" DESC", StringComparison.OrdinalIgnoreCase) Then
isDescending = True
propertyToBeSortedName = sortByParam.Split(" ")(0)
ElseIf sortByParam.EndsWith(" ASC", StringComparison.OrdinalIgnoreCase) Then
propertyToBeSortedName = sortByParam.Split(" ")(0)
End If
For Each p In properties
If p.Name.Equals(propertyToBeSortedName, StringComparison.OrdinalIgnoreCase) Then
propertyToBeSorted = p
Exit For
ElseIf p.CustomAttributes.Count(Function(c) c.AttributeType = GetType(ColumnAttribute)) > 0 Then 'Check column attribute if exists
Dim columnAttribute = p.GetCustomAttribute(Of ColumnAttribute)
If columnAttribute.Name.Equals(propertyToBeSortedName, StringComparison.OrdinalIgnoreCase) Then
propertyToBeSorted = p
Exit For
End If
End If
Next
If propertyToBeSorted IsNot Nothing Then
If isDescending Then
If sortingList Is Nothing Then
sortingList = list.OrderByDescending(Function(o) propertyToBeSorted.GetValue(o))
Else
sortingList = sortingList.ThenByDescending(Function(o) propertyToBeSorted.GetValue(o))
End If
Else
If sortingList Is Nothing Then
sortingList = list.OrderBy(Function(o) propertyToBeSorted.GetValue(o))
Else
sortingList = sortingList.ThenBy(Function(o) propertyToBeSorted.GetValue(o))
End If
End If
End If
Next
If sortingList IsNot Nothing Then
Return sortingList
Else
Return list
End If
End Function
End Module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment