Search code examples
c#listsorting

Custom List Sort by Part of String


Apologies if this question has already been answered, but none of my searches returned what I'm looking for.

What I need is a method to sort a list of strings, but the sorting needs to be done by a substring (contains) of the string in the list.

For example:

R10.14_R15.2.2b - Upgrade - Even
R10.14_R15.2.2c - Upgrade - Odd
R10.14_R15.2.2 - Upgrade - Prx

These are the list items. The order needs to always be (case insensitive):

  1. String containing the "PRX" substring.
  2. String containing the "ODD" substring.
  3. String containing the "EVEN" substring.

So the upper list should look like this after being sorted:

R10.14_R15.2.2 - Upgrade - Prx
R10.14_R15.2.2c - Upgrade - Odd
R10.14_R15.2.2b - Upgrade - Even

Also, the strings in the list do not always follow the same pattern and the "PRX", "ODD", "EVEN" substring can appear in any place inside of the strings. Additionally the strings do not always contain the same numbers. This is why the ask is to sort by using contains.

I have tried introducing a custom IComparer class, but I had no luck with this approach. Any help is appreciated.


Solution

  • var strings = new List<string>{
        "R10.14_R15.2.2b - Upgrade - Even",
        "R10.14_R15.2.2c - Upgrade - Odd",
        "R10.14_R15.2.2 - Upgrade - Prx"
    };
    
    var orderedStrings = strings.OrderBy(s => {
       if(s.Contains("prx", StringComparison.OrdinalIgnoreCase)) return 1;
       if(s.Contains("odd", StringComparison.OrdinalIgnoreCase)) return 2;
       if(s.Contains("even", StringComparison.OrdinalIgnoreCase)) return 3;
       return 4;
    })