gpt4 book ai didi

asp.net - 计算列表中项目的出现次数

转载 作者:行者123 更新时间:2023-12-02 01:48:04 26 4
gpt4 key购买 nike

看看这段代码:

 @foreach (var item in Model.Categories)
{
<li><a href="#">@item</a></li>
}

Model.Categories 是包含博客类别的字符串列表。该列表包含多次出现的同一类别,我想像这样显示结果:

音乐(5)

其中 5 是音乐类别下的博文数量。有关如何执行此操作的任何提示?

最佳答案

一点点 Linq 会有所帮助。尝试使用 GroupBy方法,像这样:

@foreach (var group in Model.Categories.GroupBy(c => c))
{
<li><a href="#">@group.Key (@group.Count())</a></li>
}

当然,您也可以在 Controller 操作中执行此操作(我在猜测变量名称):

...
viewModel.PostCounts =
(from p in db.Posts
group p by p.Category into g
select new PostCountViewModel
{
CategoryName = g.Key,
PostCount = g.Count()
})
.ToList();

return View(viewModel);

然后在你看来:

@foreach (var item in Model.PostCounts)
{
<li><a href="#">@item.CategoryName (@item.PostCount)</a></li>
}

如果您可以在单个查询中从数据库中提取所有帖子计数,而不必遍历内存中的集合,我通常建议使用第二个选项。我敢肯定您将不得不进行调整,但希望您能大致了解它的外观。

关于asp.net - 计算列表中项目的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24370285/

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