2010-08-17 29 views
0

这个问题是类似这样的:从一个表和最新的1行获取行从关联的表,在LINQ

LINQ to SQL: GroupBy() and Max() to get the object with latest date

但我有我要回了很多行的表从。它的主键被用作第二个表中的外键。对于从第一行返回的每一行,我也想要返回(在同一结果集中)最新的(在这种情况下,由日期时间字段排序)1行。

这将如何在LINQ中使用C#构造?

我的最好的是:

var instances = from i in ContextDB.Instances 
        join p in ContextDB.Points on i.InstanceID equals p.InstanceID 
        where categoryIDs.Contains(j.CategoryID) 
        group p by p.InstanceID into latestPoint 
        select new latestPoint.OrderBy(i => i.Instance.Title).FirstOrDefault(); 

但是,这显然是错误的。虽然我认为我正确理解group,但我不认为我正确理解into

[编辑]为了避免混淆,我认为这个问题可以概括为:“如何从一张表格中的行以及另一张表格中的最新的1行?”

+0

你需要清除你的编辑..我认为有一个错字。 – Nix 2010-08-17 13:02:58

+1

有更好的方法来做到这一点,它将开始于实体模型中的关联/关系。您的模型中的Instances/CategoryInstances/Points是否存在关联? – Nix 2010-08-17 13:04:03

+0

是的,CategoryInstances - > InstanceID(在两者中),Instances - > InstanceID上的实例(在两者中)。模式中有表引用。我将从样本中删除涉及CategoryInstances的行,因为这会导致混淆。 – 2010-08-17 13:10:30

回答

1

如何:

var instances = from i in ContextDB.Instances 
       where i.CategoryInstances.Any(categoryIDs.Contains(ci => ci.CategoryID)) 
       select new 
       { 
        Instance = i, 
        LatestPoint = i.Points.OrderBy(i => i.Instance.Title).FirstOrDefault() 
       }; 

注意,我可以using associations instead of join免去很多冗余的。

+0

有时候我会提出建议,要知道他们应该以更好的方式来做......但这是假设实例和点之间有联系的有效方法。 – Nix 2010-08-17 13:07:02

相关问题