1

I have a List(of String()). I have written a custom comparer (implements IComparer(of string)) to do an alphanumeric sort.

Is there a way to sort the List using a given index to determine which position in the String() to sort by? In other words one time I might sort by Index = 0 and another time by Index = 3. The length of all String() in the list is the same.

For reference this question is similar to Sort List<String[]> except I am using VB.net and that question is hardwired to Index=0.


EDIT from OP's comments:

I started simple with the non custom comparer but I am getting an error: expression does not produce a value. Not sure what I am doing wrong. Here is the code:

Public Shared Function SortListOfStringArray(ByVal ListOfStringArray As List(Of String()), ByVal SortByIndex As Integer) As List(Of String())
    Return ListOfStringArray.Sort(Function(x, y) x(SortByIndex).CompareTo(y(SortByIndex)))
End Function 
0

1 Answer 1

3

To sort a list of string arrays on a specific index in the array, you use:

Dim index As Integer = 1
list.Sort(Function(x, y) x(index).CompareTo(y(index)))

Using a custom comparer that would be:

Dim index As Integer = 1
list.Sort(Function(x, y) comparer.Compare(x(index), y(index)))
Sign up to request clarification or add additional context in comments.

3 Comments

I started simple with the non custom comparer but I am getting an error: expression does not produce a value. Not sure what I am doing wrong. Here is the code: Public Shared Function SortListOfStringArray(ByVal ListOfStringArray As List(Of String()), ByVal SortByIndex As Integer) As List(Of String()) Return ListOfStringArray.Sort(Function(x, y) x(SortByIndex).CompareTo(y(SortByIndex))) End Function
Sorry for the mess. I have no idea how to get a code block so the code looks clean. I'm relatively new to programming and first time posting to this site.
@tullynyguy: The Sort method doesn't return anything. First sort the list, then return it. If you want to keep the original list and return a new list, you have to copy the list before sorting it.

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.