Linq - OrderBy int列给出不正确的结果

时间:2015-04-17 10:23:47

标签: c# linq

我有以下查询,它给出了不正确的结果。我想要Order By first Year&然后By Month。所以我的结果应该是Jan 2015, Feb 2015, Mar 2015&等等。

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

以上查询为我提供了结果April 2015, August 2015, December 2015,Feb 2015&等等。它是由字母排序的Enum。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:6)

根据IEnumerable<T>.Dictinct() extension method的文档,返回的序列是无序序列。

  

Distinct(IEnumerable)方法返回一个   无序序列,不包含重复值。它使用了   default equality comparer,Default,比较值。

IQuerable<T>.Distinct() extension method的文档说的是同样的东西,这是合乎逻辑的,因为它将被翻译成任何提供者(SQL,EF)正在工作。

  

执行表达式时发生的查询行为   表示调用的树不同(IQueryable)   取决于source参数类型的实现。该   预期的行为是它返回一个无序序列   来源中的独特物品。

解决方案是选择您需要的数据,执行您的数据,然后订购结果,最后进行预测。

像这样:

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();
相关问题