简体   繁体   English

Linq查询OrderBy Multiple

[英]Linq Query OrderBy Multiple

I have a List<Employees> collection that I am trying to select Active employees on. 我有一个List<Employees>集合,我试图选择Active员工。

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: 我一定做错了,因为我在这里看到很多例子表明我可以做到这一点,但Visual Studio告诉我我不能,因为:

Cannot implicitly convert type 'System.Linq.IOrderedEnumerable' to 'System.Collections.Generic.List'. 无法将类型'System.Linq.IOrderedEnumerable'隐式转换为'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. LastNameFirstName (您可能怀疑)都是String值,而Active是布尔值。

范围变量

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

You should use ToList at the end of your query: 您应该在查询结尾处使用ToList

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();

Just append a ToList() to your query if you want the result as a list. 如果要将结果作为列表,只需将ToList()附加到查询中即可。 or simply declare emps as var emps which will have a type IOrderedEnumerable 或者简单地将var emps声明为var emps ,其类型为IOrderedEnumerable

This has been answered here before , just use the orderby keyword in linq 这已在此处得到解答 ,只需在linq中使用orderby关键字

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM