Tuesday, November 15, 2016

Extension method for OrderBy




This is an extermely useful method that can be used to order the entity object while data binding.
Source : http://extensionmethod.net/csharp/ienumerable-t/orderby-string-sortexpression

Here is the code in VB.NET.


<Extension()> _
    Public Function OrderBy(Of T)(list As IEnumerable(Of T), sortExpression As String) As IEnumerable(Of T)
        sortExpression += ""
        Dim parts As String() = sortExpression.Split(" "c)
        Dim descending As Boolean = False
        Dim [property] As String = ""

        If parts.Length > 0 AndAlso parts(0) <> "" Then
            [property] = parts(0)

            If parts.Length > 1 Then
                descending = parts(1).ToLower().Contains("esc")
            End If

            Dim prop As PropertyInfo = GetType(T).GetProperty([property])

            If prop Is Nothing Then
                Throw New Exception((Convert.ToString("No property '") & [property]) + "' in + " + GetType(T).Name + "'")
            End If

            If descending Then
                Return list.OrderByDescending(Function(x) prop.GetValue(x, Nothing))
            Else
                Return list.OrderBy(Function(x) prop.GetValue(x, Nothing))
            End If
        End If

        Return list
    End Function