views:

52

answers:

2

So, right now I've got a number of columns the user can sort by (Name, County, Active) and that's easy but messy. Looks something like this...

        Select Case e.SortExpression
            Case "Name"
                If (isDescending) Then
                    resultsList.OrderByDescending(Function(a) a.Name).ToList()
                Else
                    resultsList.OrderBy(Function(a) a.Name).ToList()
                End If
            Case "County" ... and so on

what I would LIKE to do, is something more ... graceful, like this

Private Function SortThatList(ByVal listOfStuff As List(Of Stuff), ByVal isDescending As Boolean, ByVal expression As Func(Of Stuff)) As List(Of Stuff)
    If (isDescending) Then
        Return listOfStuff.OrderByDescending(expression)
    Else : Return listOfStuff.OrderBy(expression)
    End If
End Function

but it doesn't like the datatype (Of TKey) ... I've tired Func(Of stuff, boolean) (got something in c# that works nicely like that) but can't seem to get this one to do what I want. Ideas? What's the magic syntax?

+3  A: 

Here you go, an extension method that takes an extra parameter, in VB. What you were probably missing is the (Of TSource, TKey) after the method name, equivalent of <TSource, TKey> in C#.

<Extension()>
Public Function OrderBy(Of TSource, TKey)(ByVal source As IEnumerable(Of TSource), ByVal isDescending As Boolean, ByVal selector As Func(Of TSource, TKey)) As IOrderedEnumerable(Of TSource)
    Return If(isDescending, source.OrderByDescending(selector), source.OrderBy(selector))
End Function
Julien Lebosquain
A: 

the accepted answer in c# incase anyone comes looking

public IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, bool isDescending, Func<TSource, TKey> selector)
{
    return isDescending ? source.OrderByDescending(selector) : source.OrderBy(selector);
}

usage

VB

listOfStuff.OrderBy(isDescending, Function(x) x.Name)

C#

listOfStuff.OrderBy(isDescending, x => x.Name);
jeriley