我正在为我的MVC4 webapp(在C#中)编写一个方法,该方法将获得一个Blog对象列表,并吐出一个类别及其命中的两列列表。我提供的代码问题是KeyValuePairs是不可变的。最终目标是使用此变量(修剪为前6行/对)来显示最高类别(按照该类别中任何文章的查看次数)。 我应该使用不同的变量类型还是以不同的方式进行更新?
public List<KeyValuePair<string, int>> Top6BlogCategories()
{
// Get Blog posts
IEnumerable<Blog> posts = db.Blogs.ToList();
// Get Blog Categories
IEnumerable<string> categories = Categories();
// Create a variable to hold the Category and its Hits
List<KeyValuePair<string, int>> categoryHits = new List<KeyValuePair<string,int>>();
// Populate the List's first column (Category)
foreach(var category in categories)
{
categoryHits.Add(new KeyValuePair<string, int>(category, 0));
}
// Populate the List's second column (Hits)
foreach(var row in categoryHits)
{
foreach(var post in posts)
{
if(post.Category == row.Key)
{
row.Value++;
}
}
}
return categoryHits;
}
答案 0 :(得分:1)
您应该使用ViewModel来描述您期望的响应。
例如,如果您希望向您的视图发送前6个类别及其总帖子的列表,我会使用以下内容:
视图模型:
public class TopCategoryModel
{
public string Category {get; set;}
public int Count {get; set;}
}
Controller的动作:
public IEnumerable<TopCategoryModel> Top6BlogCategories()
{
return db.Blogs
.Select(b => b.Category)
.Distinct()
.Select(c => new TopCategoryModel
{
Category = c,
Count = db.Blogs.Count(b => b.Category == c)
})
.OrderByDescending(a => a.Count)
.Take(6);
}
答案 1 :(得分:0)
您可以使用LINQ和Count吗?
public IEnumerable<Blog> Top6BlogCategories()
{
// Get Blog posts
IEnumerable<Blog> posts = db.Blogs.ToList();
// Get Blog Categories
IEnumerable<string> categories = Categories();
// Create a variable to hold the Category and its Hits
List<KeyValuePair<string, int>> categoryHits = new List<KeyValuePair<string,int>>();
// Populate the List's first column (Category)
foreach(var category in categories)
{
categoryHits.Add(new KeyValuePair<string, int>(category, posts.Count(post => post.Category == category)));
}
return posts;
}