LINQ Order BY 在 VB.NET 中使用文本值



我是 LINQ 的新手,想按自定义文字顺序排序...不确定这样做的语法(假设可能)。谢谢!

Class Foo
    Sub New(Name As String, Position As Integer)
        Me.Name = Name
        Me.Position = Position
    End Sub
    Public Name As String
    Public Position As Integer
End Class
Sub Main()
    Dim l As New List(Of Foo)
    l.Add(New Foo("Something1", 1))
    l.Add(New Foo("Something2", 2))
    l.Add(New Foo("Something3", 3))
Dim literalSort = ..... 'sort l by this literal order... "2, 3, 1"

将这个答案改编为 VB:

Dim order = New Integer() {2,3,1}
Dim literalSort = l.OrderBy(Function(i) If(order.Contains(i), 0, 1)) _ 
                   .ThenBy(Function(i) Array.IndexOf(order, i)) _
                   .ThenBy(Function(i) i)  ' sort rest numerically

鉴于您想要实现的排序看似任意的性质,我将创建一个带有 case 语句的方法,然后根据位置返回您想要的顺序:

Public Function OrderFoo (ByVal foo as Foo) as Integer
    Select Case foo.Position
        Case 2 
            Return 1
        Case 3
            Return 2
        Case 1
            Return 3
        Case Else
            Return 100
    End Select
End Function

在 LINQ 的OrderBy中调用该方法,并确保记录选择顺序的原因。

您应该能够调用如下所示的方法:

From foo In l _
Select foo _
Order By OrderFoo(foo)

这将创建一个按照 orderedNumbers 数组中指定的顺序排序的新列表:

    Dim l As New List(Of Foo)
    l.Add(New Foo("Something1", 1))
    l.Add(New Foo("Something2", 2))
    l.Add(New Foo("Something3", 3))
    Dim orderedNumbers As Integer() = {2, 3, 1}
    Dim outputList As New List(Of Foo)
    For Each num In orderedNumbers
        outputList.Add(l.Item(num - 1))
    Next

听起来您需要的是一个实现IComparer(Of Foo)的客户比较器。

下面的示例根据Value对列表中的项目进行排序,这就是我假设您所追求的。如果它不完全符合您的要求,更改它应该很容易。

Public Class SpecificListComparer
    Implements IComparer(Of Foo)
    Private _order As Integer() = {2, 3, 1}
    Public Function Compare(x As Foo, y As Foo) As Integer Implements IComparer(Of Foo).Compare
        'TODO - check for null values
        If x.Value = y.Value AndAlso x.Name = y.Name Then Return 0
        If x.Value = y.Value Then Return x.Name.CompareTo(y.Name)
        Return Array.IndexOf(_order, x.Value).CompareTo(Array.IndexOf(_order, y.Value))
    End Function
End Class

然后你只是像这样使用它:

l.Sort(New SpecificListComparer)

相关内容

  • 没有找到相关文章

最新更新