我想从数据库中获取数据并将其添加到DropDownList
以便在搜索面板中选择项目,我想从列表中删除重复项目(一位作者,多本书籍)。我该怎么办?
List<string> authorname = new List<string>();
foreach (var item in DB.Books)
{
authorname.Add(item.BookDetails.authorname.ToString());
}
ViewData["AuthorName"] = new SelectList(authorname);
答案 0 :(得分:0)
在从数据库中选择DropDownList后,使用唯一值填充DropDownList。使用&#39; distinct&#39; SQL查询中的关键字是为了实现这一目标。
SELECT DISTINCT column_name,column_name
FROM table_name;
答案 1 :(得分:0)
尝试以下
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);
答案 2 :(得分:0)
List<string> authorname = new List<string>();
foreach (string name in DB.Books.Select(x=> new {name = x.authorname}).Distinct())
{
authorname.Add(name);
}
答案 3 :(得分:0)
你可以直接使用linq并获取不同的项目..
代码
list<string> authorNamesDistinct = (from a in DB.Books
select a.BookDetails.authorname).Distinct().ToList();
ViewData["AuthorName"] = new SelectList(authorNamesDistinct);