orderby () containing numbers and letters

3.4k Views Asked by At

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?

4

There are 4 best solutions below

2
On BEST ANSWER

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);
0
On

Very simple

string[] allScenes = {"4B","1A","1","1B","2","4C"};

var result = allScenes.OrderBy(x => x.First()).ThenBy(x => x.Last());
0
On

As values are stored as string into the database you just have to write OrderBy(e=> e).

The code below proves this works:

string[] items = {"4B", "1A", "1", "1B", "2", "4C", "4"};
items.OrderBy(e=> e) 
2
On

I also have a similar issue but bit difference as below example:

 "A4B", "1A1", "123", "1B45", "2", "4C", "4-A2";

Letter or special chars might be anywhere in string list, but need to sort only by numbers. Expected result:

2, A4B, 4C, 1A1, 4-A2, 123, 1B45.