代码之家  ›  专栏  ›  技术社区  ›  jeriley

条件OrderBy

  •  1
  • jeriley  · 技术社区  · 16 年前

            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
    

    我想做的,是更多。。。优雅,就像这样

    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
    

    但它不喜欢(TKey的)数据类型。。。我已经厌倦了Func(boolean)(在c中得到了一些很好的工作方式),但似乎不能让这个做我想做的事情。思想?神奇的语法是什么?

    2 回复  |  直到 16 年前
        1
  •  3
  •   Julien Lebosquain    16 年前

    在VB中,有一个扩展方法需要一个额外的参数。你可能错过的是 (Of TSource, TKey) 在方法名之后,等价于 <TSource, TKey>

    <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
    
        2
  •  0
  •   jeriley    16 年前

    以防有人来看

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

    使用

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

    C级#

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