Search code examples
sql-serverlinqlinq-to-sqlsql-to-linq-conversion

Why my Linqued query is not giving me proper result?


I have this sql query which gives me proper result i.e all the names of employee sorted by A to Z using order by clause

select Distinct(EmpNTLogin),Employee from Attendance 
where  CreateDate>='2016-01-01'
order by EmpNTLogin

when I converted the same query in Linq,I am getting the right result but order by clause is not working. here is my Linqued Query

    var query = (from attendance in db.Attendances
                     orderby attendance.EmpNTLogin
                     where attendance.CreateDate.Value.Year >= 2016
                     select new { attendance.Employee, attendance.EmpNTLogin }).Distinct();

Solution

  • In the linq query, the distinct is applied after the orderby and therefore the order is discarded.

    Apply the orderby after the call to distinct

    var query = (from attendance in db.Attendances
                 where attendance.CreateDate.Value.Year >= 2016
                 select new
                 {
                     attendance.Employee,
                     attendance.EmpNTLogin
                 }).Distinct().OrderBy(att => att.EmpNTLogin);