Search code examples
c#linqsql-order-by

Orderby using C# LINQ


I want to convert the following SQL query in LINQ

Select * from EmpCode order by Left(EmpCode,4) Right(EmpCode4)

Is it possible to make a LINQ query like this?


Solution

  • If I can read your typos correctly

    var result = listOfEmpCode.Orderby(x => x.SubString(4))
                              .ThenBy(x => x.SubString(x.Length-4))
                              .ToList();
    

    Note : this doesn't check for valid string length.. add pepper and salt to taste


    Enumerable.OrderBy<TSource, TKey> Method (IEnumerable, Func<TSource, TKey>)

    Sorts the elements of a sequence in ascending order according to a key.

    Enumerable.ThenBy<TSource, TKey> Method (IOrderedEnumerable, Func<TSource, TKey>)

    Performs a subsequent ordering of the elements in a sequence in ascending order according to a key.

    String.Substring Method (Int32, Int32)

    Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

    Getting Started with LINQ in C#