2

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();
akash
  • 173
  • 1
  • 14

2 Answers2

5

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);
Silvermind
  • 5,791
  • 2
  • 24
  • 44
0

You need to first apply the 'where' clause and then apply the 'orderby' clause. Something like this :

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