11

我目前正在通过一个表(“Table1”)“分页”,该表具有以下字段 { Policy、Name、Amount、Date},并且“Table1”中可以有多个记录用于策略,如下所示:

return context.Table1s.Orderby(i => i.Policy)
                      .Skip(endingRecord).Take(page)
                      .ToList();

如果我想首先按策略分组,然后跳过并采用不同的策略(基本上是试图确保“页面”包含页面中包含的策略的所有记录),我该怎么做?

我正在使用 C#、实体框架,如果可能的话,我更喜欢“lambda”语法。

4

3 回答 3

9
return context.Table1s.GroupBy(i => i.Policy)
                      .Select(g => g.First())
                      .Orderby(i => i.Policy)
                      .Skip(endingRecord).Take(page)
                      .ToList();

这会生成这样的 SQL(来自 LinqPad 的 Linq to 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]
于 2013-03-15T18:00:49.977 回答
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();
于 2013-03-15T18:51:22.373 回答
0

您可以使用SkipWhileandTakeWhile方法,但您需要将其分开如下:

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();
于 2013-03-15T17:54:42.213 回答