Home > Mobile >  Blazor, LINQ ORDER BY of String with Quarter and Year
Blazor, LINQ ORDER BY of String with Quarter and Year

Time:03-16

I have a Blazor Server .Net 6 app and I would like to use LINQ to parse a string that contains Quarter - Year (count) that will be used in a dropdown list. But I would like to order the list with the newsest first. As it’s a string I cant use the normal Order By in LINQ

Example data:
Q4 – 2022 (7)
Q3 – 2022 (9)
Q2 – 2022 (10)
Q1 – 2022 (15)
Q4 – 2021 (18)
Q3 – 2021 (5)
Q2 – 2021 (4)
Q1 – 2021 (1)

Any thoughts how I can order this string so the data will always appear in the above order

TIA

CodePudding user response:

You can use OrderBy and ThenBy along with Range as long as your data is consistent in format.

var data = new string[] {
    "Q4 – 2022 (7)",
    "Q3 – 2022 (9)",
    "Q2 – 2022 (10)",
    "Q1 – 2022 (15)",
    "Q4 – 2021 (18)",
    "Q3 – 2021 (5)",
    "Q2 – 2021 (4)",
    "Q1 – 2021 (1)"};

var orderedData = data.OrderBy(d=> d[5..9]).ThenBy(d => d[1..2]);

This orders by the characters at positions 6 to 9 (the year) and then orders by the characters at 1 to 2 (the quarter). It is crucial that the data always matches that pattern for this to work.

Try it out

  • Related