Search code examples
c#linqasp.net-core-2.2

string sorting in LINQ


I have below data in database.

01-001-A-02
01-001-A-01
01-001-B-01
01-002-A-01
01-003-A-01

From above, I want sorted data as below:

01-001-A-01
01-001-A-02
01-001-B-01
...

My query as below

var l = _context.Locs.OrderBy(o => o.loc).Take(3);

//result of the Query
01-001-A-01
01-002-A-01
01-003-A-01

Here is my table structure

public class Location
{
      [Key]
      public int id { get; set; }
      public string loc { get; set; }
      public bool isEmpty { get; set; }
}

I am using Asp.Net Core 2.2, Code-First approach. This is not a computed coloumn.

Sorting is required from right part to left after split by '-'

What am I missing in my LINQ query?


Solution

  • You can order by each part of string separately (splitted by -) using string.Split method:

      string[] strArr = { "01-001-A-02", "01-001-A-01", "01-001-B-01", "01-002-A-01", "01-003-A-01", };
      strArr = strArr
        .Select(s => new { Str = s, Splitted = s.Split('-') })
        .OrderBy(i => i.Splitted[0])
        .ThenBy(i => i.Splitted[1])
        .ThenBy(i => i.Splitted[2])
        .ThenBy(i => i.Splitted[3])
        .Select(i => i.Str).ToArray();
    

    Note that this requires each element to have four parts (separated by -). Otherwise, it will throw t.