Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Select method of linq to EF sorting the output list?

I have Shifts table in SQL Server db

RecID   ShiftTime   StartTime   EndTime
1       Day         06:40       15:45
2       After       15:46       23:30
3       Night       23:31       06:39
4       ShortDay    06:40       12:30
5       MiddDay     12:31       19:00

RecID - int, ShiftTime, StartTime and EndTime - varchar(20)

When I evaluate following linq query
var shiftsNames = context.Shifts.Select(s => s.ShiftTime);
it is sorts the output as After, Day, MiddDay, Night, ShortDay.

In this form
var shifts = context.Shifts.ToList();
var shiftsNames = shifts.Select(s=>s.ShiftTime).ToList();
linq works as expected without sorting.

like image 422
Michael Avatar asked Dec 28 '25 20:12

Michael


1 Answers

The first query returns the sorting from SQL server - which is not specified in the query, so you cannot assume anything about the order.
Same goes for the second query, but there the default "unsorted" order seems to work.
Add sorting if you need it.

Try this in SQL:

Select * from table
Select col from table

Which will most probably get different sort order. This is what you see here.

like image 53
Lev Avatar answered Dec 30 '25 23:12

Lev