列表中的多个排序<of t =“”> </of>

时间:2011-04-01 15:03:47

标签: vb.net linq list generics sorting

我正在使用VB.NET和.NET framework 3.0

我目前正在对这样的列表进行排序:

  lstPeople.Sort(Function(p1, p2) p1.LName.CompareTo(p2.LName))

但是,现在我想在LName之后按FName排序。因此,它首先按姓氏排序,然后按名字排序。

这可能吗?

5 个答案:

答案 0 :(得分:1)

  

这可能吗?

是的,只需编写一个实现所需排序的比较器。所以先比较姓氏;如果它们不相等则返回CompareTo的结果,如果它们不相等则返回名字之间的比较。

答案 1 :(得分:1)

是的,这是可能的。 我认为最好的方法是,如果您可以更改“人员”类,则创建自己的CompareTo()函数。

Private Function CompareTo(p2 As People) As Integer
    Dim i As Int32 = Me.LName.CompareTo(p2.LName)
    If i = 0 Then
        Return Me.FName.CompareTo(p2.FName)
    End If
    Return i
End Function

然后使用它:

  lstPeople.Sort(Function(p1, p2) p1.CompareTo(p2))   

编辑:转换为VB.NET。

答案 2 :(得分:0)

尝试

Public Class PeopleComparer
    Implements IComparer(Of People)

    Public Function Compare(x As People, y As People) As Integer
         Dim lnameComparison As Integer = x.LName.CompareTo(y.LName)
         Return If(lnameComparison = 0, x.FName.CompareTo(y.FName), lnameComparison)
    End Function
End Class

lstPeople.Sort(New PeopleComparer())

答案 3 :(得分:0)

必须将

Implements System.Collections.Generic.IComparer(Of People).Compare添加到该函数中。通过在IComparer(Of People)

之后键入enter键生成存根
Public Class PeopleComparer
    Implements IComparer(Of People)

    Public Function Compare(x As People, y As People) As Integer Implements System.Collections.Generic.IComparer(Of People).Compare
        Dim lnameComparison As Integer = x.LName.CompareTo(y.LName)
        Return If(lnameComparison = 0, x.FName.CompareTo(y.FName), lnameComparison)
    End Function
End Class

答案 4 :(得分:0)

Bala R的答案基本上是正确的,但我必须向编译器提供更多信息,以便克服您所看到的编译器错误:

Public Class PeopleComparer
    Implements IComparer(Of People)

    Public Function Compare(x As People, y As People) As Integer Implements IComparer(Of People).Compare
         Dim lnameComparison As Integer = x.LName.CompareTo(y.LName)
         Return If(lnameComparison = 0, x.FName.CompareTo(y.FName), lnameComparison)
    End Function
End Class

lstPeople.Sort(New PeopleComparer())