我目前通过表(“Table1”)“分页”,其中包含以下字段{Policy,Name,Amount,Date},并且“Table1”中可以有多个记录,如下所示:< / p>
return context.Table1s.Orderby(i => i.Policy)
.Skip(endingRecord).Take(page)
.ToList();
如果我想首先按策略分组然后跳过并采用不同的策略(基本上试图确保“页面”包含页面中包含的策略的所有记录),我将如何执行此操作?/ p>
我正在使用C#,实体框架,如果可能,更喜欢“lambda”语法。
答案 0 :(得分:7)
return context.Table1s.GroupBy(i => i.Policy)
.Select(g => g.First())
.Orderby(i => i.Policy)
.Skip(endingRecord).Take(page)
.ToList();
生成这样的SQL(从LinqPad到Linq到SQL的示例):
SELECT [t4].[test], [t4].[Name], [t4].[Policy], [t4].[Amount], [t4].[Date]
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY [t3].[Policy]) AS [ROW_NUMBER], [t3].[test], [t3].[Name], [t3].[Policy], [t3].[Amount], [t3].[Date]
FROM (
SELECT [t0].[Policy]
FROM Table1s AS [t0]
GROUP BY [t0].[Policy]
) AS [t1]
OUTER APPLY (
SELECT TOP (1) 1 AS [test], [t2].[Name], [t2].[Policy], [t2].[Amount], [t2].[Date]
FROM Table1s AS [t2]
WHERE (([t1].[Policy] IS NULL) AND ([t2].[Policy] IS NULL)) OR (([t1].[Policy] IS NOT NULL) AND ([t2].[Policy] IS NOT NULL) AND ([t1].[Policy] = [t2].[Policy]))
) AS [t3]
) AS [t4]
WHERE [t4].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
ORDER BY [t4].[ROW_NUMBER]
答案 1 :(得分:1)
以下给出了我想要的结果
return context.Tables1
.Where(i =>
context.Tables1
.GroupBy(t => t.Policy)
.OrderBy(t => t.Key)
.Skip(previousRecordCount).Take(page)
.Select(t => t.Key)
.Contains(i.Policy))
.ToList();
答案 2 :(得分:0)
您可以使用SkipWhile
和TakeWhile
方法,但您需要按如下方式将其分开:
var policyStart = context.Table1s.Orderby(i => i.Policy).ToList().SkipWhile(i => i.Policy == endingRecord.Policy);
var firstPolicy = policyStart.FirstOrDefault().Policy;
return policyStart.TakeWhile(i => i.Policy == firstPolicy).ToList();