Link to home
Create AccountLog in
Avatar of culminIT
culminITFlag for South Africa

asked on

Sort LINQ result, integers first then strings

Hi all

I am getting back results from a LINQ query. The results are gathered from an object with its own members and public properties which in turn gets its data from the DB. This result is loaded into a combobox I create in code and is attached to a datagridview.

The issue is that it is a combination of integers and strings, such as the following:

1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, 15+, not answered.

The problem is, that with this combination it is sorted as a list of strings. Like this:

1, 10, 11, 12, 13, 14, 15+, 2, 3, 4, 5, 6, 7, 8, 9, not answered.

Is there any way to sort the list so that the integers come first and then the strings, such as the top list indicates?

Thank you
Avatar of Gautham Janardhan
Gautham Janardhan


 var temp = "1,+,3,10,5,6,7,8,9,4,11,12,13,14,15,2".Split(",".ToCharArray()).ToList();
var temp2 = temp.OrderBy(new Func<string, int>(orderBy)).ToList();


public int orderBy(string b)
        {
            int value;

            if (int.TryParse(b, out value))
            {
                return value;
            }
            else
            {
                return int.MaxValue;
            }
        }

Open in new window

oops forgot it was VB find VB variant below
Sub Main()
        Dim temp As List(Of String) = "1,+,3,10,5,6,7,8,9,4,11,12,13,14,15,2".Split(",".ToCharArray()).ToList()
        Dim temp2 As List(Of String) = temp.OrderBy(Function(arrayValue) orderBy(arrayValue))
    End Sub


    Private Function orderBy(ByVal value1 As String) As Boolean
        Dim value As Integer
        If (Integer.TryParse(value1, value)) Then
            Return value
        Else
            Return Integer.MaxValue
        End If
    End Function

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of culminIT
culminIT
Flag of South Africa image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer