Search code examples
c#linq

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


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"]

Solution

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