patel.milanb
patel.milanb

Reputation: 5982

multiple Orderby and Sort

I have 2 classes:

 Employee
 EmployeeDetails

I would like to have a list with first ordering of Employee then sort it, then EmployeeDetails orderby and then sort it.

I was thinking of something like this:

var result = _db.Employee
              .OrderBy( e => e.EmpName )
              .Sort('DepartmentId') // using the diff property
              .ThenBy( ed => ed.EmpAddress )
              .Sort('PostCode'); // using the diff property

I need to first order by EmpName from Employee then Sort it after from those resultset I want to orderby EmpAddress and Sort it and then return the resultset.

Is this even possible? Can it be done without using Lambdas? Are the other approaches?

Upvotes: 5

Views: 3922

Answers (3)

Alexander Schimpf
Alexander Schimpf

Reputation: 2392

Is the following code what you're looking for?

var result = _db.Employee
                .OrderBy(e => e.EmpName)
                .ThenBy(e => e.DeptartmentId)
                .ThenBy(e => e.EmpAddresss)
                .ThenBy(e => e.PostCode);

Upvotes: 7

Kevin Aenmey
Kevin Aenmey

Reputation: 13419

If your Employee class has an EmployeeDetails property with the EmpAddress, you could do this:

var result = _db.Employee
          .OrderBy( e => e.EmpName )
          .ThenBy( e => e.EmployeeDetails.EmpAddress );

Upvotes: 1

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79889

You are looking for:

var result = _db.Employee
              .OrderBy( e => e.EmpName )  //OrderBy and SortBy empname  Ascending
              .ThenBy( ed => ed.EmpAddress ); //orderby address ascending

Upvotes: 1

Related Questions