简体   繁体   English

LINQ-根据上一个孩子的状况获得父母

[英]LINQ - get parent based on last child condition

I have the current entities: 我有当前实体:

Students (Id, Name,..) 学生(编号,姓名,..)

Grades (Id, Student_Id, Grade) 成绩(编号,学生编号,成绩)

A student can have more of no grades.. 一个学生可以有更多的没有成绩。

Using LINQ (Entity Framework) how can I get a list of all students that have the last grade different than 10! 使用LINQ(实体框架),我如何获得所有最后成绩不超过10的学生的列表!

I was trying: 我正在尝试:

var students = db.students.Where(c => c.Grades.LastOrDefault().Grade != 10) .ToList(); 

The problem is since I may not have any grades, the LastOrDefault can be null . 问题是由于我可能没有任何成绩,因此LastOrDefault可以为null

Nobody seems to notice that Last(Ordefault) is not supported in LINQ to Entities. 似乎没有人注意到LINQ to Entities不支持Last(Ordefault) So you have to use another approach: 因此,您必须使用另一种方法:

var students = db.students
                 .Where(c => c.Grades.OrderByDescending(g => g.Date)
                 .FirstOrDefault().Grade != 10).ToList();

I have to guess that there is some useful property by which you can order the Grades (a Date ?). 我不得不猜测,有一些有用的属性可以用来排序成绩( Date ?)。 You don't want to depend on the order the database happens to produce them. 您不想依赖数据库碰巧产生它们的顺序。

As said in a comment, null values don't throw exceptions in SQL, the language in which this expression is evaluated. 如评论中所述,空值不会在SQL(该表达式的计算语言)中引发异常。

You can simply check for existence of Grades before calling Last() as in 您可以在调用Last()之前简单地检查Grades是否存在,如下所示:

var students = db.students
    .Where(c => c.Grades.Count() > 0 && c.Last().Grade != 10)
    .ToList()

Or as pointed out in the comment, you can take advantage of the Any() function 或者如注释中指出的那样,您可以利用Any()函数

var students = db.students
    .Where(c => c.Grades.Any() && c.Last().Grade != 10)
    .ToList()

If you are using C# 6 (.NET 4.6 or higher), you can use the new Elvis Operator .? 如果使用的是C#6(.NET 4.6或更高版本),则可以使用新的Elvis Operator。 together with the Null coalesing operator. 与Null合并运算符一起使用。

var students = db.students.Where(c => c.Grades.LastOrDefault()?.Grade != 10 ?? false).ToList(); 

Basically the elvis operator will return null, if LastOrDefault() is null, else it will return the value of Grade 基本上,elvis运算符将返回null,如果LastOrDefault()为null,则它将返回Grade的值

Two other possible ways: Check if c.Grades has any values or to check if LastOrDefault() returns null. 其他两种可能的方法:检查c.Grades是否具有任何值,或者检查LastOrDefault()是否返回null。 Way 1: 方法1:

var students = db.students.Where(c => c.Grades.LastOrDefault() == null ? false : c.Grades.LastOrDefault().Grade != 10).ToList(); 

Way 2: 方式2:

var students = db.students.Where(c => c.Grades.Any() && c.Grades.LastOrDefault().Grade != 10).ToList(); 

In all 3 ways the result for students is a list where every student has at least 1 grade where the last one is not 10. 在所有3种方法中,学生的结果都是一个列表,其中每个学生至少有1个年级,而最后一个不是10年级。

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

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