我有一个包含列的小部件表"名称"和"伯爵"
"伯爵"字段包含每个窗口小部件将显示的帖子数:
Name | Count --------------------- RecentNews | 6 SpecialNews | 5 NewsGallery | 10
与小部件表和帖子表关联的第二个表:
PostID | WidgetID ------------------ 100 | 6 101 | 5 102 | 10
为了获得更高的性能,我只需通过此查询获取每个Widget的最后需要的帖子:
var postInWidgets = db.PostWidgets
.GroupBy(pw => pw.WidgetID)
.SelectMany(g => g.OrderByDescending(p => p.Post.DateCreated).Take(500))
.ToList();
然后在每个小部件中发帖:
var postsInGalery = postInWidgets
.Where(wid => wid.WidgetID == 1).Take(6)
.ToList();
var postsInSpecialNews=postInWidgets
.Where(wid => wid.WidgetID == 2).Take(5)
.ToList();
var postsInRecentNews=postInWidgets
.Where(wid => wid.WidgetID == 5).Take(10)
.ToList();
并在每个窗口小部件部分视图中:
foreach(var p in Model.PostsInRecentNews)
{
<li>@Html.ActionLink(p.Post.Title,"Index","Home")</li>
}
我的问题:如何为每个小部件动态设置Take(count)的int值而不是Take(6),Take(5),Take(10)...
我认为我需要使用TakeWhile()而不是Take()
感谢您的帮助......
答案 0 :(得分:1)
听起来你只需要先获取计数(你可能想要缓存它们):
var counts = db.Counts.ToDictionary<string, int>(c => c.Name, c => c.Count);
然后:
var postsInGallery = postInWidgets
.Where(wid => wid.WidgetID == 1)
.Take(counts["NewsGallery"])
.ToList();
var postsInSpecialNews = postInWidgets
.Where(wid => wid.WidgetID == 2)
.Take(counts["SpecialNews"])
.ToList();
var postsInRecentNews = postInWidgets
.Where(wid => wid.WidgetID == 5)
.Take(counts["RecentNews"])
.ToList();
您可以使用枚举而不是字符串,以避免使用容易拼写的字符串常量。如果枚举具有相关窗口小部件ID的值,则可以将其包装在单个方法中:
List<Widget> GetWidgets(WidgetType widgetType)
{
return postInWidgets.Where(wid => wid.WidgetID == (int) widgetType)
.Take(counts[widgetType])
.ToList();
}
然后将其称为:
var postsInGallery = GetWidgets(WidgetType.NewsGallery);
var postsInSpecialNews = GetWidgets(WidgetType.SpecialNews);
var postInRecentNews = GetWidgets(WidgetType.RecentNews);
(这假定counts
是一个字段,当然 - 根据您的要求进行调整。)