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?
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.
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).
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.
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.
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.
You can use a custom comparison to sort the list:
nList.Sort(Function(x, y) x.zIndex.CompareTo(y.zIndex))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With