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 a List<string> based on the string after last index of the string c#

I’m wanting to be able to re-order a list based on the lastindexof a character in this case "/".

var ListToSort = new List<string> { "Hjgs/dasdf/ada/2toe0685tcr1/Hello_1",
            "Hjgs/dasdf/ada/xdt42pj616ao/Yes_1",
            "Hjgs/dasdf/ada/7yhzozo2rgu5/Hello_2",
            "Hjgs/dasdf/ada/atrejl1rzliq/Yes_2",
            "Hjgs/dasdf/ada/bgwq9i8fbsj4/Hello_3",
            "Hjgs/dasdf/ada/4rrx4pldbiq1/Zues_1"};

im wanting to sort the list based on the last index of "/" eg it would compare Yes_1,Hello_2 and so on , the expected output would be:

            
            Hjgs/dasdf/ada/2toe0685tcr1/Hello_1
            Hjgs/dasdf/ada/7yhzozo2rgu5/Hello_2
            Hjgs/dasdf/ada/bgwq9i8fbsj4/Hello_3
            Hjgs/dasdf/ada/xdt42pj616ao/Yes_1
            Hjgs/dasdf/ada/atrejl1rzliq/Yes_2
            Hjgs/dasdf/ada/4rrx4pldbiq1/Zues_1

edit : working solution from comments

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

ListToSort = ListToSort.OrderBy(x => x.Substring(x.LastIndexOf("/"))).ToList();

>Solution :

using System;
using System.Collections.Generic;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        var ListToSort = new List<string> { "Hjgs/dasdf/ada/2toe0685tcr1/Hello_1",
            "Hjgs/dasdf/ada/xdt42pj616ao/Yes_1",
            "Hjgs/dasdf/ada/7yhzozo2rgu5/Hello_2",
            "Hjgs/dasdf/ada/atrejl1rzliq/Yes_2",
            "Hjgs/dasdf/ada/bgwq9i8fbsj4/Hello_3",
            "Hjgs/dasdf/ada/4rrx4pldbiq1/Zues_1"};
        
        foreach(var item in ListToSort.OrderBy(x => x.Substring(x.LastIndexOf("/"))))
            Console.WriteLine(item);
    }
}
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