使用LINQ按最新日期获取所有记录(来自单个表)

时间:2017-12-19 09:32:16

标签: c# linq

我正在尝试使用LINQ获取最新日期的所有记录(来自单个表)但有一些问题。例如,如果表有2行具有最新日期,那么我需要在某些条件下获取这两行。请帮忙

这是我的代码。

var q = (from n in Table
         where n.CustomerId == customerId && n.Isactive==true
         group n by new { n.CustomerId, n.ConsentId } into grp
         select new
         {
            // select all fields
            grp.Key.ConsentId,
            grp.Key.CustomerId,
            Date = grp.Max(t=>t.CreatedOn)
         }).ToList(); 

2 个答案:

答案 0 :(得分:1)

您必须将CustomerId+ConsentId - 组拆分为子组(CreatedOn):

var q = Table
    .Where(x => x.CustomerId == customerId && x.Isactive)
    .GroupBy(x => new { x.CustomerId, x.ConsentId })
    .SelectMany(g => g
        .GroupBy(x => x.CreatedOn.Date).OrderByDescending(x => x.Key).First()
        .Select(x => new
        {
            g.Key.ConsentId,
            g.Key.CustomerId,
            Date = x.CreatedOn // this is the max-date per group
        }));

答案 1 :(得分:0)

据我了解,您需要Table中的所有记录,这些记录属于具有特定ID(IsActive = true)的活动(CustomerId = <id>)客户,并且该记录必须是最新的(max(CreatedOn) )。我不明白什么是ConsentId,你真的需要它吗? 您已经完成了一半的解决方案,您获得了该客户的max(CreatedOn)值。现在,您只需要为此客户选择表格中的行,并CreatedOn = founded max

var q1 = from n in Table
            join max in (from n1 in Table
                        where n1.CustomerId == customerId && n1.Isactive==true
                        group n1 by new { n1.CustomerId, n1.ConsentId }
                        into grp
                        select new { grp.Key.CustomerId, grp.Key.ConsentId, MaxCreatedOnDate = grp.Max(r => r.CreatedOn) }) 
            on new { CustomerId = n.CustomerId, ConsentId = n.ConsentId, date = n.CreatedOn } equals new { CustomerId = max.CustomerId, ConsentId = max.ConsentId, date = max.MaxCreatedOnDate }
            select n;

UPD。 如果表中有多个组(CustomerId,ConsentId),则内部查询(它是您的查询)可以提供多于一行。如果仅需要CustomerId的组,则删除查询中的所有ConsentId外观。

相关问题