Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
LINQ与大多数孩子一起成为父母_Linq_Entity Framework - Fatal编程技术网

LINQ与大多数孩子一起成为父母

LINQ与大多数孩子一起成为父母,linq,entity-framework,Linq,Entity Framework,我有一个父对象的列表,它有一个子对象的列表。我需要编写一个查询,该查询将为我提供子项最多的父项。ORM是实体框架,因此它应该与实体框架配合使用 以以下代码开头: parents.FirstOrDefault(c => c.Children.Max()); 类似的东西。我认为它应该更像这样: parents.OrderByDescending(p => p.Children.Count()).FirstOrDefault(); 您的查询不正确,因为c.Children.Max()将

我有一个
父对象的列表,它有一个
子对象的列表。我需要编写一个查询,该查询将为我提供子项最多的父项。ORM是实体框架,因此它应该与实体框架配合使用

以以下代码开头:

parents.FirstOrDefault(c => c.Children.Max());

类似的东西。

我认为它应该更像这样:

parents.OrderByDescending(p => p.Children.Count()).FirstOrDefault();
您的查询不正确,因为
c.Children.Max()
将尝试迭代一个父项的子项,如果它们支持比较(例如,子项是int),则只返回其中最大的一个。而且很可能您的子对象不是bool,因此您甚至无法编译代码,因为FirstOrDefault需要

Expression<T, bool>
表达式

您不需要为此进行排序:

int maxChildCount = parents.Max(x => x.Children.Count());
var maxParent = parents.FirstOrDefault(p => p.Children.Count() == maxChildCount);
或作为查询表达式:

var maxParent = (from p in parents
                 let max = parents.Max(x => x.Children.Count())
                 where p.Children.Count() == max).FirstOrDefault();

这不是要访问每一张唱片两次吗?这会比订单花费更长的时间吗?是的-它必须遍历两次,因此它是
O(2n)
=
O(n)
,其中as排序是
O(n lg n)
。假设这是通过EF查询提供程序完成的,但排序+选择顶部(1)很可能在内部进行了优化,以实际执行得更好。@BrokenGlass因此Validmir的答案在内存中和转换为存储表达式时都更有效?@Lolcoder:不在内存中否,如果列表中有4个以上的元素,我的方法将更加有效。在存储表达式上,这取决于EF/SQL如何优化查询计划-我现在不知道。