显示LINQ查询中不同书名的列表

时间:2015-03-09 19:58:07

标签: asp.net-mvc linq

我有一个视图,我想显示一个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>

1 个答案:

答案 0 :(得分:1)

如果您想使用当前的模型,该模型需要Book的集合而不是字符串集合,请使用GroupByBook的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();