![](/img/trans.png)
[英]How to get group of records with latest date using Linq to Entities
[英]Get all records (from single table) by latest date using LINQ
我正在尝试使用LINQ在最新日期之前获取所有记录(从单个表中获取),但是有一些问题。 例如,如果表中有两行具有最新日期,那么我需要根据特定条件来获取这两行。 请帮忙
这是我的代码。
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();
您必须将CustomerId+ConsentId
-group分成一个子组(通过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
}));
据我了解,您需要来自Table的所有记录,这些记录属于具有特定ID( CustomerId = <id>
)的active( IsActive = true
)客户,并且该记录必须是最新的( 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),则内部查询(它是您的查询)可以提供多于1行。 如果只需要按CustomerId分组,则删除查询中所有ConsentId外观。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.