如果我有以下两个models
:
public class Book
{
public int ID { get; set; }
public string Title { get; set; }
//other properties
public virtual Category Category { get; set; }
}
public class Category
{
public int ID { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
我将List<Book>
发送到视图:
public class ShopController : Controller
{
private BookStoreMDFEntities db = new BookStoreMDFEntities();
public ActionResult Index()
{
var list = db.Books.Include("Category").ToList();
return View(list);
}
}
如何查看此Book
列表中每个类别的类别名称和出现次数?
示例输出:
答案 0 :(得分:0)
如果您使用的是Entity Framework,则可以执行以下操作:
var list = db.Category.Select(c =>
new {
Name = c.CategoryName,
Count = c.Books.Count
}).ToList();
然后将其发送到您的视图并使用Razor中的@foreach
进行渲染。
如果您确实需要发送List<Book>
来进行查看,您可以在视图中对书籍进行分组:
@{
var list = Model.GroupBy(b => b.Category.CategoryName);
}
@foreach (var entry in list)
{
<div>@entry.Key : @entry.Count()</div>
}