LINQ只与具有列最大值的行保持联接

时间:2015-03-30 10:22:38

标签: c# sql oracle linq

我有一个表 ProjectInformation 为(左表)

ProjectID int
{fields}

另一个表 ProjectUpdates (右表)。此表具有每月添加1个ProjectID的多条记录。

ProjectID int
CreateDate date
{other fields that have records}

他们的关系是1-M。 样本数据

ProjectInformation
{ ProjectID = 1, DataA = "ABC"}
{ ProjectID = 2, DataA = "DEF"}
{ ProjectID = 3, DataA = "GHI"}

ProjectUpdates
{ProjectID = 1, CreateDate = "24/2/2014", DataB = "JKL"}
{ProjectID = 1, CreateDate = "25/1/2014", DataB = "MNL"}
{ProjectID = 1, CreateDate = "23/12/2014", DataB = "PQR"}
{ProjectID = 1, CreateDate = "23/11/2014", DataB = "STU"}
{ProjectID = 2, CreateDate = "24/2/2014", DataB = "VWX"}
{ProjectID = 2, CreateDate = "24/1/2014", DataB = "YZA"}
{ProjectID = 3, CreateDate = "21/12/2014", DataB = "BCD"}
{ProjectID = 3, CreateDate = "24/11/2014", DataB = "EFG"}
{ProjectID = 3, CreateDate = "24/10/2014", DataB = "HIJ"}
{ProjectID = 3, CreateDate = "24/8/2014", DataB = "KLM"}
{ProjectID = 3, CreateDate = "24/6/2014", DataB = "NOP"}

我希望我的LINQ查询返回以下数据(每个项目1行)

标准:左表中的行将与右侧的行连接,该项具有项目的 CreateDate 的最大值。

{ProjectID = 1, CreateDate = "24/2/2014", DataA ="ABC", DataB = "JKL"}
{ProjectID = 2, CreateDate = "24/2/2014", DataA ="DEF", DataB = "VWX"}
{ProjectID = 3, CreateDate = "21/12/2014", DataA ="GHI", DataB = "BCD"}

3 个答案:

答案 0 :(得分:2)

您可以使用ProjectInformation与ProjectUpdate和OrderByDescending / FirstOrDefault之间的one to many关联。

public class ProjectInformation {
  public int ProjectID { get; set; }
  public virtual ICollection<ProjectUpdate> ProjectUpdates { get; set; }
}

db.Project
  .Select(p => new {
    ProjectID = p.ProjectID,
    MostRecentProjectUpdate = p.ProjectUpdates.OrderByDescending(u => u.CreateDate).FirstOrDefault()
});

注意:如果CreateDate是数据库中的字符串而不是日期,则使用OrderByDescending可能会很棘手。

答案 1 :(得分:2)

你可以做很多事。其中一种方式是:

var result = (from pi in projectInformations
              join pu in projectUpdates on pi.ProjectID equals pu.ProjectID into tpu
              from t in tpu.OrderByDescending(c => c.CreateDate).Take(1)
              select new { pi.ProjectID, pi.DataA, t.CreateDate, t.DataB }).ToList();

答案 2 :(得分:0)

试试这个: -

var result = (from pi in projectInfo
              join pu in projectupdates
              on pi.ProjectID equals pu.ProjectID into g
              let data = g.OrderByDescending(x => DateTime.ParseExact(x.CreateDate, 
                           "dd/M/yyyy", CultureInfo.InvariantCulture)).FirstOrDefault()
              select new
              {
                  ProjectID = data.ProjectID,
                  CreatedDate = data.CreateDate,
                  DataA = pi.DataA,
                  DataB = data.DataB
               }).ToList();

Working Fiddle

请注意,由于我使用FirstOrDefault,您需要在访问其属性之前检查数据是否为空。