Search code examples
c#wpflinqlinq-to-sqlsql-order-by

orderby () containing numbers and letters


I want to order an array containing numbers and letters in an ascending order the values are stored as a string in a DB.

This is the list I have

4B
1A
1
1B
2
4C
4

and want them to order like this where numbers are ascending followed by letters alphabetically.

1
1A
1B
2
4
4B
4C

So far I tried

 allScenes.OrderBy(x => Convert.ToInt32(x.SceneNumber)).ToList()

and

 allScenes.OrderBy(x => Convert.int.parse(x.SceneNumber)).ToList()

but both don't work because of the letters after the number. Any idea how I can make this work?


Solution

  • Given your example data where the first number is always a single digit:

    allScenes.OrderBy(x => x.SceneNumber).ToList()
    

    If you can possibly have multi-digit numbers, please provide them and where you want them in the sort order.

    This is one way to sort multiple digit numbers:

    var allScenes = new[]{
      new {SceneNumber="4B"},
      new {SceneNumber="1A"},
      new {SceneNumber="1"},
      new {SceneNumber="1B"},
      new {SceneNumber="2"},
      new {SceneNumber="14"},
      new {SceneNumber="4C"},
      new {SceneNumber="14A"},
      new {SceneNumber="200"},
      new {SceneNumber="200A"},
      new {SceneNumber="200B"}
      };
    var nums="0123456789".ToCharArray();
    var result=allScenes
      .OrderBy(x=>x.SceneNumber.LastIndexOfAny(nums))
      .ThenBy(x=>x.SceneNumber);
    

    Results:

    1 
    1A 
    1B 
    2 
    4B 
    4C 
    14 
    14A 
    200 
    200A 
    200B 
    

    The database may not be able to convert the LastIndexOfAny function to something SQL-like, so you may need to do an .ToList() before the .OrderBy():

    var nums="0123456789".ToCharArray();
    var result=allScenes
      .ToList()
      .OrderBy(x=>x.SceneNumber.LastIndexOfAny(nums))
      .ThenBy(x=>x.SceneNumber);