LINQ 在 GROUP BY 之前使用表的值时出现问题
我有以下 GROUP BY:
var stocks =
from p in products
from w in p.Warehouses
from l in w.locations
group l by l.Date into g
let maxDate = g.Max(l1 => l1.Date)
select new { Product=p.Name, Location= g.Where(l2 => l2.Date == maxDate) };
但它不起作用,我认为因为我正在进行分组,所以不允许在我的选择中使用分组之前的表中的值。
这是对象的层次结构。
Products
Each product has multiple warehouses
Each warehouse has multiple locations.
我需要退回所有产品,并且每个产品都必须包含位置名称。
当有多个仓库、多个地点时,找地点的标准是什么?
我必须在每个仓库中进行搜索,然后在每个位置中进行搜索...并返回所有位置中的最新位置(只有 1 个),这是我使用 Date == maxDate
检测到的。
但它不会让我选择 p 中的“名称”。它不在 g 中,因为 g 是按“位置”分组的。
I have the following GROUP BY:
var stocks =
from p in products
from w in p.Warehouses
from l in w.locations
group l by l.Date into g
let maxDate = g.Max(l1 => l1.Date)
select new { Product=p.Name, Location= g.Where(l2 => l2.Date == maxDate) };
But it isn't working, i think because I am doing a group by I am not allowed to use values from the tables before the group by in my select.
Here is the hierarchy of the objects.
Products
Each product has multiple warehouses
Each warehouse has multiple locations.
I need to return all products and each product must contain the location name.
What is the criteria to find the location when there are multiple warehouses and multiple locations.
I must search in each warehouse and in turn each location... and return OUT OF ALL OF THEM the latest location (ONLY 1) which I detect using the Date == maxDate
.
But it won't let me select the "Name" that was in p. It's not in g as g is group by of "locations".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想你想要这样的东西:
请注意,如果没有匹配的位置,
Location
可能为空。这里不需要使用
let
子句,但我认为这将是编写查询的最易读的方式。当然,现在您实际上并不需要对所有位置进行排序...但是 LINQ 中没有 MaxBy,而这才是您真正想要的。如果您使用 LINQ to Objects,您可以编写自己的
MaxBy
方法(MoreLINQ);在 LINQ to SQL 等中,我希望数据库无论如何都能优化查询。I think you want something like this:
Note that
Location
may be null, if there are no matching locations.There's no need to use a
let
clause here, but I figured this would be the most readable way of writing the query.Now you don't really need to sort all the locations, of course... but there's no
MaxBy
in LINQ, which is what you really want. If you're using LINQ to Objects you could write your ownMaxBy
method (and there's one in MoreLINQ); in LINQ to SQL etc I'd expect the database to optimize the query anyway.