简体   繁体   English

使用LINQ .OrderByDescending无法正常工作

[英]Using LINQ .OrderByDescending not working

I am trying to build a query where there is one student name then a nested collection of clubs he belongs to. 我正在尝试建立一个查询,其中有一个学生姓名,然后是他所属的俱乐部的嵌套集合。 I want to organize this collection with OrderByDescending. 我想使用OrderByDescending组织此集合。 I am stuck with what to provide to the parenthesis. 我对提供括号的内容感到困惑。

public void GetStudentsClubNameRev()
        {
            try
            {
                using (SchoolContainer = new SchoolContainer())
                {

                    var query = from student in SchoolContainer.Students
                                select new
                                {
                                    StudentName = student.Name,
                                    ClubName = student.StudentClubMatches
                                        .Where(s =>s.StudentId == student.Id)
                                        .Select(c => c.Club.Name)
                                        .OrderByDescending(o => "Name")
                                };
                }
            }
            catch (Exception ex)
            {

            }
        }

In .OrderByDescending(o => "Name") I don't know what my predicate is. 在.OrderByDescending(o =>“ Name”)中,我不知道我的谓词是什么。 I want to say orderbydescending on the Name which is club name. 我想说的是名称,即俱乐部名称。 But I get errors because I don't think I understand what it wants. 但是我收到错误消息是因为我不明白我想要什么。

edmx的屏幕截图

After you've selected "Club.Name", the current enumerable is just a string. 选择“ Club.Name”之后,当前的可枚举值只是一个字符串。 You just want a pass-through selector: 您只需要一个传递选择器:

.Select(c => c.Club.Name)
.OrderByDescending(name => name)

If you OrderByDescending before Select you could also do this: 如果在Select之前订购OrderByDescending,也可以执行以下操作:

var query = from student in SchoolContainer.Students
    select new
    {
        StudentName = student.Name,
        ClubName = student.StudentClubMatches
            .Where(s =>s.StudentId == student.Id)
            .OrderByDescending(c => c.Club.Name)
            .Select(c => c.Club.Name)
    };

Cheers 干杯

To sort by a property you should use the following: 要按属性排序,应使用以下命令:
Code: 码:

.OrderByDescending(o => o.Name)

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

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