0

在 vb.net Linq 中,我想按一个值对列表进行排序,但如果该值为 null,则应该使用另一个值。

样本 :

Class Item
    Public _Id As Integer
    Public _FullName As String
    Public _Acronym As String

    Public Sub New(ByVal id As Integer, ByVal fullName As String, ByVal acronym As String)
        Me._Id = id
        Me._FullName = fullName
        Me._Acronym = acronym
    End Sub
End Class

 Sub Main()
        Dim itemList As New List(Of Item)
        itemList.Add(New Item(1, "AZZ", "A"))
        itemList.Add(New Item(2, "BBB", "B"))
        itemList.Add(New Item(3, "FFF", "F"))
        itemList.Add(New Item(4, "An item", Nothing))

        itemList = (From l In itemList Order By l._Acronym).ToList

        For Each i In itemList
            Debug.Print(String.Format("{0}{2}{1}", i._Acronym, i._FullName, IIf(i._Acronym IsNot Nothing, " - ", "")))
        Next
    End Sub

这种结果:

An item
A - AZZ
B - BBB
F - FFF

我想要的结果:

A - AZZ
An item
B - BBB
F - FFF

因为“An”应该在“A”之后。

排序需要使用 Acronym,但是如果 acronym 什么都没有,则应该使用 Fullname。我们不能将 FullName 的值放入结果中的 Acronym 中。它可以作为一种排序方法来完成,但结果列表需要保留首字母缩写词的原始值。

4

3 回答 3

1

C#

ItemList.OrderBy(x=>x._Acronym??x._FullName);

VB.NET

ItemList.OrderBy(Function(x) If(x._Acronym, x._FullName))
于 2013-06-05T21:16:20.187 回答
1

您可以使用 VB.NET 的IF功能

itemList = (From l In itemList Order By If(l._Acronym Is Nothing, l._Id, l._Acronym)).ToList
于 2013-06-05T21:18:58.640 回答
0

向您的班级添加额外的属性怎么样 - 类似于:

Public ReadOnly Property Sorter As String
    Get
        If _Acronym Is Nothing Then Return _FullName Else Return _Acronym
    End Get
End Property

然后,您只需将 LINQ 更改为基于该属性而不是 _Acronym 进行排序。

这对你有用吗?(PS - 我很快就做到了,我不确定我是否正确创建了该属性,但我相信它应该是你正在寻找的东西)

于 2013-06-05T21:13:18.817 回答