简体   繁体   中英

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?

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

Very simple

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

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

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM