2

I have a list of strings where I need to sort it by the ending substring. For example, assume we have these strings in the list:

Get_USER_By_ID

Get_Product_By_Name

Get_Product_By_ID

Get_Location_By_Name

...

I Need to sort it so that all the functions matching the same By_ are after each other

I could loop over the list, and create many new lists, and if the string contains a specific string (i.e. By_ID), I add it to its related List.

I want to sort them in the same list (same as if I say sort ascending or descending for instance) rather than creating many new lists (in my case I have to create 9 new lists)

7
  • Is the naming always consistent in some way? i.e. they always have "By_" in them? Commented Sep 29, 2019 at 4:00
  • yep it is consistent Commented Sep 29, 2019 at 4:00
  • You can do it using swapping. Commented Sep 29, 2019 at 4:04
  • 1
    names.OrderBy(name => name.Split(new[] {"By_"}, StringSplitOptions.None).Last()) Commented Sep 29, 2019 at 4:06
  • 2
    you just need to add ToList() to the call suggested by @Fabio Commented Sep 29, 2019 at 4:30

2 Answers 2

2

You could create Custom Comparer. IComparer defines how to compare objects of type T. This could be used with List.Sort for customized Sorting of the collection. For example, for the input collection

var strList = new List<string>
            {
             "Get_USER_By_ID",
             "Get_Product_By_Name",
             "Get_Product_By_ID",
             "Get_Location_By_Name"
             };

You could sort by

strList.Sort(new CustomStringComparer());

Or using Linq

 var result = strList.OrderBy(x=>x,new CustomStringComparer());

Where CustomStringComparer is defined as

public class CustomStringComparer : IComparer<string>
{
    private Regex _regex = new Regex(@"By_(?<Tag>[\S]*)",RegexOptions.Compiled);
    public int Compare(string first, string second)
    {
        var firstSubString = _regex.Match(first).Groups["Tag"].Value;
        var secondSubString = _regex.Match(second).Groups["Tag"].Value;
        return firstSubString.CompareTo(secondSubString);
    }
}

Ouput

Get_USER_By_ID 
Get_Product_By_ID 
Get_Product_By_Name 
Get_Location_By_Name 
Sign up to request clarification or add additional context in comments.

Comments

0
myList = myList.OrderBy(str => str.Split(new[] {"By_"}, StringSplitOptions.None)
               .Last()).ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.