25

I have a list (i.e. Dim nList as new List(of className)). Each class has a property named zIndex (i.e. className.zIndex). Is it possible to sort the elements of the list by the zIndex variable in all of the elements of the list?

3 Answers 3

45

Assuming you have LINQ at your disposal:

Sub Main()
    Dim list = New List(Of Person)()
    'Pretend the list has stuff in it
    Dim sorted = list.OrderBy(Function(x) x.zIndex)
End Sub

Public Class Person
    Public Property zIndex As Integer
End Class

Or if LINQ isn't your thing:

Dim list = New List(Of Person)()
list.Sort(Function(x, y) x.zIndex.CompareTo(y.zIndex))
'Will sort list in place

LINQ offers more flexibility; such as being able to use ThenBy if you want to order by more than one thing. It also makes for a slightly cleaner syntax.

Sign up to request clarification or add additional context in comments.

5 Comments

I was unable to use the LINQ example, how would I enable that? I got the second one to work though, thanks :)
@DalexL It depends on the framework version you are targeting. You need 3.5 or greater. The VB.NET Compiler should import the System.Linq namespace for you. (Look on the References tab of the Project's properties).
OK, I am comparing dates. When I use my line a.Sort(Function(x, y) x.DelegationDate.CompareTo(y.DelegationDate)), it doesn't sort at all. It leaves it in the original order.
@JayImerman I think you should start a new question with more information about the classes and dates you are trying to sort, and more could around your example.
My list was defined as Dim list = new List(Of Person) and I had to use list = list.OrderBy(Function(x) x.zIndex).ToList to get the sorted list.
8

You can use a custom comparison to sort the list:

nList.Sort(Function(x, y) x.zIndex.CompareTo(y.zIndex))

2 Comments

@DalexL: You import the System.Linq namespace.
@DalexL: Note that you don't need Linq for the solution that I suggested.
6

If not LINQ, then you can implement the IComparable(Of ClassName) to your class:

Public Class ClassName
  Implements IComparable(Of ClassName)

  'Your Class Stuff...

  Public Function CompareTo(ByVal other As ClassName) As Integer Implements System.IComparable(Of ClassName).CompareTo
    If _ZIndex = other.ZIndex Then
      Return 0
    Else
      If _ZIndex < other.ZIndex Then
        Return -1
      Else
        Return 1
      End If
    End If
  End Function
End Sub

and then from your code:

nList.Sort()

1 Comment

You can shorten that entire CompareTo method to Return _ZIndex.CompareTo(other.ZIndex)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.