Search code examples
c#sortingtlist

Composite sort in List<string> C#


Friends, I have a List like this:

var filenames = new List<string> 
{ 
    "150_A_1_A", 
    "150_A_1",  
    "149_2",  
    "149_1",  
    "150_1_A",  
    "150_A_2",  
    "150_2_A"  
};

and I need to sort these List in an such way to get the following order:

149_1
149_2
150_1_A
150_2_A
150_A_1
150_A_1_A

Any idea? thanks


Solution

  • Hers's a LINQ expression doing what you need :

    var x = filenames.Select(s => new { value = s, splitted = s.Split('_') }).OrderBy(s => int.Parse(s.splitted[0]));
    
    for (int i = 1; i < x.Max(s => s.splitted.Length); i++)
    {
        var thisI = i;
        x = x.ThenBy(s => thisI >= s.splitted.Length ? null : s.splitted[thisI]);
    }
    
    var sorted = x.Select(s => s.value);
    

    First I split the strings by '_'

    Then I sort the first field numerically.

    Finally I sort all the remaing fields alphabetically