forX
forX

Reputation: 2153

Vb.net Linq order by special

In vb.net Linq, I want to sort a list by a value, but if the value is null, it should use another value.

Sample :

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

Result with this sort :

An item
A - AZZ
B - BBB
F - FFF

Result I want :

A - AZZ
An item
B - BBB
F - FFF

Because "An" should be after "A".

The sort need to use Acronym, but if acronym is nothing, it should use Fullname. We cant put the value of FullName into Acronym in the result. it could be done as a method to sort but the result list need to keep the original value of acronym.

Upvotes: 0

Views: 2795

Answers (3)

Yuriy Galanter
Yuriy Galanter

Reputation: 39777

You can use VB.NET's IF function

itemList = (From l In itemList Order By If(l._Acronym Is Nothing, l._Id, l._Acronym)).ToList

Upvotes: 1

Robert McKee
Robert McKee

Reputation: 21477

C#

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

VB.NET

ItemList.OrderBy(Function(x) If(x._Acronym, x._FullName))

Upvotes: 1

John Bustos
John Bustos

Reputation: 19564

What about adding an extra property to your class - Something along the lines of:

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

Then you just change your LINQ to sort based upon that property rather than _Acronym.

Would that work for you?? (PS - I did this really quickly, I'm not sure I created that property correctly, but it should be what you're looking for, I believe)

Upvotes: 0

Related Questions