我有一个视图,我想显示一个DISTINCT书名列表。我的问题是我得到...... GenericList不能分配给模型类型......
如果删除LINQ语句的不同部分,我会收到所有书籍,但它们包含重复项。我只想要一份清单。感谢
这就是我所拥有的:
控制器:
public ActionResult Chapters(string book)
{
var chapter = (from b in Bible.Books
where b.Name == book
select b.Name);
return View(chapter);
}
@model IEnumerable<BibleApp.Models.Book>
@{
ViewBag.Title = "All Books";
}
<h2>All</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
</tr>
<ul class="list-unstyled">
@foreach (var book in Model)
{
<li><a href="">@Html.DisplayFor(x => book.Name)</a></li>
}
</ul>
</table>
答案 0 :(得分:1)
如果您想使用当前的模型,该模型需要Book
的集合而不是字符串集合,请使用GroupBy
对Book
的Name属性进行分组,然后获取该组中的First
成员,如:
var chapter = Bible.Books
.GroupBy(b=> b.Name)
.Select(grp=> grp.First());
return View(chapter);
这会根据不同的Book
为您提供Name
个项目的集合。
如果您可以修改View
以接受IEnumerable<string>
模型,那么您可以使用现有代码(如果您只对Book的名称和
var chapter = (from b in Bible.Books
where b.Name == book
select b.Name).Distinct();
return View(chapter);
或使用方法语法:
var chapter = Bibile.Books.Select(b=> b.Name).Distinct();