forX
forX

Reputation: 2153

linq sub list vb.net, sort by sub value

Its how to working with sub list (in vb.net).

I have a list of Item. each Item contain a list of Item2. I need to sort where Item.ListOf(Item2).value contain "ValueX".

Sample :

 Dim myList As New List(Of Niveau1)
        For i As Integer = 1 To 3
            Dim niv1 As New Niveau1(i)
            For j As Integer = i To i + 1
                niv1.listOfNiveau2.Add(New Niveau2(j))
            Next
            myList.Add(niv1)
        Next


Class Niveau1
    Public id As Integer
    Public listOfNiveau2 As List(Of Niveau2)
    Public Sub New(ByVal id As Integer)
        Me.listOfNiveau2 = New List(Of Niveau2)
        Me.id = id
    End Sub
End Class

Class Niveau2
    Public id As Integer
    Public value As String
    Public Sub New(ByVal id As Integer)
        Me.id = id
        Me.value = String.Format("Value{0}", id Mod 3)
    End Sub
End Class

the actual result is a listOf(Niveau1)

I need to sort the list (mylist). The result will put at first, every item Niveau1 where listOfNiveau2 contain an item where value = "Value0", and after those, every other item.

The result should be this list:

Item 1 :
   id = 2
   listOfNiveau2 = 
            { id = 2, value = "Value1" }
            { id = 3, value = "Value0" }

Item 2 :
   id = 3
   listOfNiveau2 = 
            { id = 3, value = "Value0" }
            { id = 4, value = "Value1" }

Item 3 :
   id = 1
   listOfNiveau2 = 
            { id = 1, value = "Value1" }
            { id = 2, value = "Value2" }

The first and second item contain "Value0" it their sub list, thats why their at first on the list. We add every other item after them. In this sample, we just have 1 item left.

If we want the string "Value2" instead of "Value0". the result should be:

Item 1 :
   id = 1
   listOfNiveau2 = 
            { id = 1, value = "Value1" }
            { id = 2, value = "Value2" }

Item 2 :
   id = 2
   listOfNiveau2 = 
            { id = 2, value = "Value1" }
            { id = 3, value = "Value0" }

Item 3 :
   id = 3
   listOfNiveau2 = 
            { id = 3, value = "Value0" }
            { id = 4, value = "Value1" }

because the Item with id=1 is the only one containing a listOfNiveau2 containing the value "Value2"

Upvotes: 1

Views: 656

Answers (1)

Dave Williams
Dave Williams

Reputation: 2246

Ok I got it in the end...

myList.OrderBy(Function(x) x.id).ThenBy(Function(x) If(x.listOfNiveau2.Any(Function(y) y.value = "Value2"), 0, 1))

you can substitute "Value2" with a variable and it should work.

Just in case... it works by ordering on Int32 (either 0 , 1) which is determined by seeing if the List contains any niveau2 with a value that you passed in. I have tested it and it seems to work fine. Let me know if you have any problems.

I can forsee that a list which is not sorted first by Id will return the items out of order therefore I have added the OrderBy.ThenBy as well.

Upvotes: 3

Related Questions