0

In my generic list contain integer and string value. how do i perform OrderBy or OrderByDescending.

For example

  List<String> codelst = new List<string>() { "1","2","3","4","5","10","100","a12","b12" };
  codelst.OrderBy(g => g);

It shows like as follows

1    
10  
100    
2    
3    
5     
a12    
b12

but need to show

1        
2    
3    
5    
10  
100  
a12   
b12

if I have convert to int it shows input string error

codelst.OrderBy(g => Convert.ToInt32(g));

How to achieve this

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
Hisanth
  • 62
  • 2
  • 9
  • Use the overload of `OrderBy` that accepts an `IComparer`. Then implement the `IComparer` as you need it. For example, see [Alphanumeric/natural sorting in C# using IComparer](http://snipd.net/alphanumericnatural-sorting-in-c-using-icomparer). – Georg Patscheider Apr 23 '18 at 12:05
  • @CodeCaster that's not a duplicate because this is about a mix of numbers and digits – Impostor Apr 23 '18 at 12:07
  • @Dr.Snail It is also the solution for this question. – Matthew Watson Apr 23 '18 at 12:08
  • 2
    @MatthewWatson and 10 years later `[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]` is still the way to go? – Impostor Apr 23 '18 at 12:10
  • @Dr.Snail Why wouldn't it be? After all, the CLR runtime classes use large amounts of the Windows API in their implementation - for example, OpenFile() - despite it being more than 25 years old... But yes, the answer is: It is still the way to go. – Matthew Watson Apr 23 '18 at 12:24
  • You can do this: `codelst.OrderBy(g => new Tuple(g.ToCharArray().All(char.IsDigit)? int.Parse(g) : int.MaxValue, g))`. btw, I don't like the idea of using a `DllImport` for this; also no idea why this has been reported duplicate of a question which is asking for sorting a `FileInfo` array; although it has answers in non accepted answers, but still, it is weird. – mshsayem Apr 23 '18 at 13:26

0 Answers0