Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a VB.net List by a class value

Tags:

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?

like image 857
Freesnöw Avatar asked Jun 25 '11 15:06

Freesnöw


People also ask

How do I sort a list of objects in VB net?

Using the OrderBy() Method in LINQ The most common way of sorting lists is by using the OrderBy() LINQ method to create a new, sorted copy of the original list. This creates a new list with the elements sorted by using a key. This key should be a property of the object.

What is searching and sorting in VB?

Searching here refers to finding an item in the array that meets some specified criterion. Sorting refers to rearranging all the items in the array into increasing or decreasing order (where the meaning of increasing and decreasing can depend on the context).

How to use collection in VB net?

You can use the Visual Basic Collection class to access a collection item by using either a numeric index or a String key. You can add items to a collection object either with or without specifying a key. If you add an item without a key, you must use its numeric index to access it.

What do you mean by collection in VB net?

VB.NET implements a special object called the Collection object that acts as a container for objects of all types. In fact, Collection objects can hold other objects, as well as nonobject data. In some ways, the Collection object is an object-oriented version of the Visual Basic array.


2 Answers

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.

like image 149
vcsjones Avatar answered Oct 07 '22 23:10

vcsjones


You can use a custom comparison to sort the list:

nList.Sort(Function(x, y) x.zIndex.CompareTo(y.zIndex)) 
like image 43
Guffa Avatar answered Oct 07 '22 23:10

Guffa