如何在视图中返回不同的名称?我无法将我的distinct()方法返回的字符串强制转换为Inumerable对象。
为简化起见,如果您在数据库中看到一个名为John Smith的人,我们假设John Smith的所有引用都来自同一个人。
数据
id name quote
1 Finn Mathematical
2 Jake Aw, man!
3 Shredder Tonight, I dine on turtle soup.
4 Shredder Nooooo
型号
namespace Quotes_Sample.Models
{
public class QuoteDB
{
public int Id { get; set; }
public string name { get; set; }
public string quote { get; set; }
public bool IsSelected { get; set; }
}
public class QuoteDBContext : DbContext
{
public DbSet<QuoteDB> Quotes { get; set; }
}
}
控制器
private QuoteDBContext db = new QuoteDBContext();
// GET: Quotes
public ActionResult Index()
{
return View(db.Quotes.ToList());
}
查看
@model IEnumerable<Quotes_Sample.Models.QuoteDB>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<p>
@Html.ActionLink("Create New", "Create")
</p>
@using (Html.BeginForm("SubmitSelected", "Quotes", FormMethod.Post, new { encType = "multipart/form-data", name="myform"}))
{
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.name)
</th>
</tr>
@foreach (var item in (IEnumerable<Quotes_Sample.Models.QuoteDB>)Model.Select(x => x.name).Distinct())
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.name)
</td>
</tr>
}
</table>
}
</body>
</html>
An exception of type 'System.InvalidCastException' occurred in App_Web_cied5w21.dll but was not handled in user code
Additional information: Unable to cast object of type '<DistinctIterator>d__81`1[System.String]' to type 'System.Collections.Generic.IEnumerable`1[Quotes_Sample.Models.QuoteDB]'.
以下内容:
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.name)
</th>
</tr>
@foreach (string name in Model.Select(x => x.name).Distinct())
{
<tr>
<td>
@Html.DisplayText(name);
</td>
</tr>
}
</table>
但这真让我感到奇怪。它给了我以下内容:
name
;
;
;
感谢您的耐心和帮助。
答案 0 :(得分:2)
您可以使用以下命令获取Distinct
个记录:
Model.GroupBy(x => x.name).Select(x => x.First())
但是你应该在Controller
而不是View
。
您也可以使用DistinctBy
方法:
Model.DistinctBy(x => x.name)