I a currently "paging" through a table ("Table1") that has the following fields { Policy, Name, Amount, Date} and there can be mulitple records in "Table1" for a policy, like the following:
return context.Table1s.Orderby(i => i.Policy)
.Skip(endingRecord).Take(page)
.ToList();
How would I do this if I wanted to first group by Policy and then skip and take on the distinct policies (basically trying to ensure that a "page" contains all the records for the policies included in the page)?
I'm using C#, entity framework and prefer the "lambda" syntax if possible.
return context.Table1s.GroupBy(i => i.Policy)
.Select(g => g.First())
.Orderby(i => i.Policy)
.Skip(endingRecord).Take(page)
.ToList();
That generates SQL like this (sample from LinqPad for 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]
The following gave me the desired results
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With