[英]C# MVC4 Variable to Hold Two Columns That Can Be Updated
我正在為MVC4 Web應用程序(使用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;
}
您應該使用ViewModel來描述您期望的響應。
例如,如果您希望向列表發送前6個類別及其帖子總數的列表,我將使用以下方式:
視圖模型:
public class TopCategoryModel
{
public string Category {get; set;}
public int Count {get; set;}
}
管制員的行動:
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);
}
您可以使用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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.