从数据库MVC4的下拉列表中删除重复项
本文关键字:删除 下拉列表 数据库 MVC4 | 更新日期: 2023-09-27 18:17:41
我想从DB中获取数据并将其添加到DropDownList
,以便在搜索面板中选择一个项目,我想从列表中删除重复的项目(一个作者,许多书籍)。我该怎么办?
List<string> authorname = new List<string>();
foreach (var item in DB.Books)
{
authorname.Add(item.BookDetails.authorname.ToString());
}
ViewData["AuthorName"] = new SelectList(authorname);
try below
List<string> authorname = new List<string>();
foreach (var item in DB.Books)
{
if(!authorname.Contains(item.BookDetails.authorname.ToString()))
authorname.Add(item.BookDetails.authorname.ToString());
}
ViewData["AuthorName"] = new SelectList(authorname);
用从数据库中选择的唯一值填充DropDownList。在SQL查询中使用'distinct'关键字来实现这个目标。
SELECT DISTINCT column_name,column_name
FROM table_name;
http://www.w3schools.com/sql/sql_distinct.asp List<string> authorname = new List<string>();
foreach (string name in DB.Books.Select(x=> new {name = x.authorname}).Distinct())
{
authorname.Add(name);
}
您可以直接使用linq获取不同的项。
代码
list<string> authorNamesDistinct = (from a in DB.Books
select a.BookDetails.authorname).Distinct().ToList();
ViewData["AuthorName"] = new SelectList(authorNamesDistinct);