user153923
user153923

Reputation:

Linq Query OrderBy Multiple

I have a List<Employees> collection that I am trying to select Active employees on.

I must be doing something wrong, because I see numerous examples on here showing that I can do this, yet Visual Studio is telling me I can not because:

Cannot implicitly convert type 'System.Linq.IOrderedEnumerable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)

What is wrong with this picture? LastName and FirstName (as you might suspect) are both String values, and Active is a Boolean.

range variable

DataGridView1.DataSource = null;
List<AcpEmployee> emps = from e in employeeInfo.Employees
                         where e.Active 
                         orderby e.LastName, e.FirstName descending
                         select e;

Upvotes: 2

Views: 8601

Answers (3)

lucusc
lucusc

Reputation: 23

This has been answered here before, just use the orderby keyword in linq

var emps = from e in employeeInfo.Employees 
            where e.Active orderby e.LastName thenby e.FirstName select e;

Upvotes: 1

L.B
L.B

Reputation: 116178

Just append a ToList() to your query if you want the result as a list. or simply declare emps as var emps which will have a type IOrderedEnumerable

Upvotes: 4

Lee
Lee

Reputation: 144206

You should use ToList at the end of your query:

List<AcpEmployee> emps = (  from e in employeeInfo.Employees
                            where e.Active
                            orderby e.Active orderby e.LastName, e.FirstName descending
                            select e).ToList();

or using the methods directly:

List<AcpEmployee> emps = employeeInfo.Employees
    .Where(e => e.Active)
    .OrderBy(e => e.LastName)
    .ThenByDescending(e => e.FirstName)
    .ToList();

Upvotes: 9

Related Questions