Home > Enterprise >  Order a list by substring
Order a list by substring

Time:08-31

Trying to order a list of strings

    List<string> strings = new List<string>() { "N3 2021","N4 2021","N1 2022","N2 2022","N4 2022","N3 2022","N2 2023","N1 2023","N3 2023"};

    var orderedList = strings.OrderBy(x => x.Substring(2).Trim()).ToList();

    Console.WriteLine(String.Join(", ", orderedList));

Current Output:

N3 2021, N4 2021, N1 2022, N2 2022, N4 2022, N3 2022, N2 2023, N1 2023, N3 2023

Desired Output:

N3 2021, N4 2021, N1 2022, N2 2022, N3 2022, N4 2022, N1 2023, N2 2023, N3 2023

Any help will be appreciated. Thanks

Update:

Solution is:

List<string> strings = new List<string>() { "N3 2021","N4 2021","N1 2022","N2 2022","N4 2022","N3 2022","N2 2023","N1 2023","N3 2023"};
    
var orderedList = strings.OrderBy(x => x.Substring(2).Trim()).ThenBy(y=>y).ToList();
    
Console.WriteLine(String.Join(", ",orderedList));

CodePudding user response:

Seems to me you are sorting by year and then by some sort of prefix code. Since the year is more significant you need to move it to the left of the code for sorting purposes.

static string RearrangeString(string input)
{
    var tokens = input.Split(' ');
    return string.Join(" ", tokens.Reverse() );
}

public static void Main()
{
    var strings = new List<string>() { "N3 2021","N4 2021","N1 2022","N2 2022","N4 2022","N3 2022","N2 2023","N1 2023","N3 2023"};
    var orderedList = strings.OrderBy(RearrangeString).ToList();

    Console.WriteLine(String.Join(", ", orderedList));
}

Fiddle

CodePudding user response:

Actually solution provided by the author, see question edit.

Here is a fiddle

using System;
using System.Collections.Generic;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        List<string> strings = new List<string>() { "N3 2021","N4 2021","N1 2022","N2 2022","N4 2022","N3 2022","N2 2023","N1 2023","N3 2023"};
    
        var orderedList = strings.OrderBy(x => x.Substring(2).Trim()).ThenBy(y=>y.Substring(0)).ToList();
    
        Console.WriteLine(String.Join(", ",orderedList));
        Console.ReadLine();
    }
}
  •  Tags:  
  • c#
  • Related