OrderBy not having any effect in LINQ

冷暖自知 提交于 2019-12-31 05:09:47

问题


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

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;

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

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:


回答1:


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

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

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



回答2:


.Distinct destroys order. Switch the position of the Distinct and the OrderBy calls.



来源:https://stackoverflow.com/questions/50131872/orderby-not-having-any-effect-in-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!