gpt4 book ai didi

c# - 在 EntityFramework 中选择每个组中的前 n 行

转载 作者:太空狗 更新时间:2023-10-29 21:08:48 24 4
gpt4 key购买 nike

我正在尝试获取每种类型的最新内容,目前我正在使用类似于以下代码的代码来获取每种类型的 n 条记录

int n = 10;
var contents = Entities.OrderByDescending(i => i.Date);

IQueryable<Content> query = null;
for (int i = 1; i<=5; i++)
{
if (query == null)
{
query = contents.Where(c => c.ContentTypeIndex == i).Take(n);
}
else
{
query = query.Concat(contents.Where(c => c.ContentTypeIndex == i).Take(n));
}
}

另一种解决方案是创建 SP,但是否可以通过在 EF 中分组来实现?如果没有,是否有更清洁的解决方案?

最佳答案

contents.Where(c => c.ContentTypeIndex >= 1 && c.ContentTypeIndex <= 5)
.GroupBy(c => c.ContentTypeIndex)
.SelectMany(g => g.Take(n));

注意:如果要选择所有类型的索引,那么这里不需要where过滤器。

关于c# - 在 EntityFramework 中选择每个组中的前 n 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23336811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com