Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading