Anup
Anup

Reputation: 9738

Linq - OrderBy int column gives incorrect results

I have the following query which gives me Incorrect results. I want to Order By first Year & then By Month. So My results should be Jan 2015, Feb 2015, Mar 2015 & so on.

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 as April 2015, August 2015, December 2015,Feb 2015 & so on. It is Ordering by Alphabets which is Enum.

What I am doing wrong here?

Upvotes: 3

Views: 830

Answers (1)

Maarten
Maarten

Reputation: 22945

According to the documentation of the IEnumerable<T>.Dictinct() extension method the returned sequence is an unordered one.

The Distinct(IEnumerable) method returns an unordered sequence that contains no duplicate values. It uses the default equality comparer, Default, to compare values.

And the documentation of the IQuerable<T>.Distinct() extension method says the same thing, which is logical since it will be translated to whatever provider (SQL, EF) is working.

The query behavior that occurs as a result of executing an expression tree that represents calling Distinct(IQueryable) depends on the implementation of the type of the source parameter. The expected behavior is that it returns an unordered sequence of the unique items in source.

The solution is to select the data you need, perform your distinct, then order your result, and finally do your projection.

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();

Upvotes: 6

Related Questions