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

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);
    }
}

Leave a Reply