我有一个包含职位描述栏和日期列的表。我想按照描述分组后得到每行的行号,如下所示。
Description RunDate rn
File Cleanup 2013-12-30 00:00:00.0000000 +00:00 1
File Cleanup 2013-12-29 00:00:00.0000000 +00:00 2
Billing Extract 2013-12-30 00:00:00.0000000 +00:00 1
Billing Extract 2013-12-30 00:00:00.0000000 +00:00 2
Billing Extract 2013-12-29 00:00:00.0000000 +00:00 3
Unit Data Extract 2013-12-05 00:00:00.0000000 +00:00 1
Monthly Extract 2013-12-05 00:00:00.0000000 +00:00 1
我能够使用以下查询在SQL中实现此目的
SELECT [Description], RunDate, rn = ROW_NUMBER()
OVER (PARTITION BY [Description] ORDER BY RunDate DESC)
FROM BackgroundJobs
我无法将其转换为Linq to SQL。我尝试使用
var jobGroups = context.BackgroundJobs.GroupBy(g => new{g.Description, g.RunDate}).Select((jobs, index) => new { RowCount = index++, BackgroundJob = jobs }).Tolist();
输出
Description RunDate rn
File Cleanup 2013-12-30 00:00:00.0000000 +00:00 1
File Cleanup 2013-12-29 00:00:00.0000000 +00:00 2
Billing Extract 2013-12-30 00:00:00.0000000 +00:00 3
Billing Extract 2013-12-30 00:00:00.0000000 +00:00 4
Billing Extract 2013-12-29 00:00:00.0000000 +00:00 5
Unit Data Extract 2013-12-05 00:00:00.0000000 +00:00 6
Monthly Extract 2013-12-05 00:00:00.0000000 +00:00 7
Linq to SQL查询增加了行号,但在描述更改时没有重置为1。
当组描述在linq中更改为SQL时,请告知如何将行号重置为1.
谢谢 Mahita
答案 0 :(得分:3)
你很接近,但你必须更深一级地进行Select
指数:
var jobGroups =
context.BackgroundJobs
.GroupBy(job => new { job.Description, job.RunDate })
.Select(g => new
{
g.Key,
Jobs = g.Select((job,i) => new
{
RowCount = i + 1,
job
})
})
.Tolist();
在AsEnumerable()
之前可能需要Select(g => ...
,因为在LINQ到SQL后端的许多实现中,不支持Select
的索引重载。