2

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;
nawfal
  • 62,042
  • 48
  • 302
  • 339
jp2code
  • 24,618
  • 35
  • 140
  • 254
  • possible duplicate of [OrderBy and List vs. IOrderedEnumerable](http://stackoverflow.com/questions/9285426/orderby-and-list-vs-iorderedenumerable) – nawfal Oct 24 '13 at 13:19

3 Answers3

9

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();
Lee
  • 133,981
  • 18
  • 209
  • 268
4

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

L.B
  • 106,644
  • 18
  • 163
  • 208
1

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;
Community
  • 1
  • 1
lucusc
  • 23
  • 4
  • 1
    `orderby` or `thenby`? It still gives the error because my code is specifically trying to assign it to a `List`. – jp2code Aug 29 '12 at 18:53
  • 1
    Ahh, I missed that assignment, L.B is right then just add the .ToList() – lucusc Aug 29 '12 at 20:10