OrderBy在LINQ中不起作用 [英] OrderBy not having any effect in LINQ

查看:280
本文介绍了OrderBy在LINQ中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,其中包含一组数据,如下所示:

I have a table that has a set of data in it, as follows:

请注意,上述结果是通过以下SQL查询收集的:

Notice the above results are gathered by the following SQL query:

select * from Logs where RegisterationId = 16 
 and date = '2018-04-13 00:00:00.000'
order by DateTime ASC;

现在这很完美,但是当我尝试使用以下方法在LINQ中做同样的事情

Now this is perfect but when I try to do the same in LINQ using:

var logs = db.Logs.Where(x => x.RegisterationId == EnrollNumber && x.Date >= StartDate &&
               x.Date <= EndDate && x.isIgnore != true).OrderBy(x => x.DateTime).Distinct().ToList();

它将所有Manual_Entry日志一起放在列表的底部/末尾(请注意下面的快照中的索引15,16和17),而不是在OrderBy DateTime中.我需要它们完全按照使用SQL查询的方式进行排序:

it gives all the Manual_Entry logs together at the bottom/at the end of the list (notice the index 15,16 & 17 in the snapshots below) and not in the OrderBy DateTime. I need them sorted exactly the way its done using SQL query:

推荐答案

正如@Ivan Stoev所述: LINQ to Entities sql转换器会忽略 Distinct/GroupBy之前的OrderBy.

As @Ivan Stoev already mentioned: OrderBy before Distinct / GroupBy is ignored by LINQ to Entities sql translator.

但是,如果必须使用它,请在OrderBy

But if you must use it, use it before the OrderBy

 var logs = db.Logs.Where(x => x.RegisterationId == EnrollNumber && x.Date >= 
                    StartDate && x.Date <= EndDate && x.isIgnore != true).Distinct().OrderBy(x => x.DateTime).ToList();

排除Distinct()应该会为您提供适当的列表:

Excluding the Distinct() should give you the appropriate list:

var logs = db.Logs.Where(x => x.RegisterationId == EnrollNumber && x.Date >= 
                   StartDate && x.Date <= EndDate && x.isIgnore != true).OrderBy(x => x.DateTime).ToList();

这篇关于OrderBy在LINQ中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆