问题
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