Home > Net >  How to sort list of string based on the second segment of each string?
How to sort list of string based on the second segment of each string?

Time:11-15

I have a list of strings that I want to sort in a descending order based on the numbers in the string, and the strings that don't have a number should come first.

["dakdmwk 2", "fwewk 1", "fmewkfmwek 4", "oopap 3", "fekamkdflew fnewjke"]

CodePudding user response:

You could use OrderByDescending with following way:

list = list
   .OrderByDescending(s => 
    { 
       var arr = s.Split(); 
       if(int.TryParse(arr.Last(),out int i))
           return i;
       return int.MaxValue;
    }).ToList();
  • Related