Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Linq-OrderBy int列给出了不正确的结果_C#_Linq - Fatal编程技术网

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

C# Linq-OrderBy int列给出了不正确的结果,c#,linq,C#,Linq,我有下面的查询,它给了我不正确的结果。我想按第一年下单,然后按月下单。所以我的结果应该是2015年1月、2015年2月、2015年3月等等 var data = ctx.tblCalendar .Where(e => e.Id == Id) .OrderBy(e => e.Year).ThenBy(e => e.MonthNo) .Select(e =>

我有下面的查询,它给了我不正确的结果。我想按第一年下单,然后按月下单。所以我的结果应该是2015年1月、2015年2月、2015年3月等等

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
上述查询的结果为2015年4月、2015年8月、2015年12月、2015年2月等。它是按字母表(即枚举)排序的


这里我做错了什么?

根据返回序列的文档,返回的序列是无序的

Distinct(IEnumerable)方法返回 不包含重复值的无序序列。它使用 默认相等比较器,默认值,用于比较值

的文档说明了同样的事情,这是合乎逻辑的,因为它将被转换为任何提供程序(SQL,EF)都在工作

由于执行表达式而发生的查询行为 表示不同调用的树(IQueryable) 取决于源参数类型的实现。这个 预期的行为是,它返回一个无序的 源中的唯一项

解决方案是选择所需的数据,执行distinct,然后对结果排序,最后进行投影

像这样:

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

Distinct通常应该保持顺序,但是对于一个实验,你可以尝试删除它,看看结果是否按你需要的方式排序。什么是
InputMonths
?注意月份是如何按字母顺序排序的。您确定
MonthNo
包含一个数值,而不是月份的实际名称吗?InputMonths是包含MonthNames Jan、Feb、Mar的枚举,…
MonthNo
包含数值…当我直接在sql中查询时,它在那里工作。