Linq - OrderBy int string gives incorrect results

I have the following query which is giving me incorrect results. I want Order By first Year

and then By Month

. So my results should be Jan 2015, Feb 2015, Mar 2015

, etc.

var data = ctx.tblCalendar
                    .Where(e => e.Id == Id)
                    .OrderBy(e => e.Year).ThenBy(e => e.MonthNo)
                    .Select(e => (InputMonths)e.Month + "-" + e.Year)
                    .Distinct()
                    .ToList();

DataType of MonthNo is int
DataType of Year is int
DataType of Month is Enum

      

The above query gives me results like April 2015, August 2015, December 2015,Feb 2015

and so on. It is an alphabetical ordering which is Enum.

What am I doing wrong here?

+3


source to share


1 answer


According to the extension method documentation, the IEnumerable<T>.Dictinct()

returned sequence is unordered.

The Distinct (IEnumerable) method returns an unordered sequence that does not contain duplicate values. It uses the default collation, the default, to compare values.

And the extension method documentation IQuerable<T>.Distinct()

says the same thing, which makes sense as it will translate to any worker (SQL, EF) worker.

The query behavior resulting from the execution of a tree expression representing a Distinct (IQueryable) call depends on the implementation of the original parameter type. the expected behavior is that it returns an unordered sequence of unique elements in the source.



The solution is to select the data you want, run your report, then streamline the result, and finally make a forecast.

Like this:

var data = ctx.tblCalendar
    .Where(e => e.Id == Id)
    .Select(e => new { e.Year, e.MonthNo, e.Month })
    .Distinct()
    .OrderBy(e => e.Year)
    .ThenBy(e => e.MonthNo)
    .Select(e => (InputMonths)e.Month + "-" + e.Year)
    .ToList();

      

+6


source







All Articles