I would like to take data from DB and add it to DropDownList
in order to select an item in search panel, I want to remove duplicates items from the list (one author, many books). What should I do?
List<string> authorname = new List<string>();
foreach (var item in DB.Books)
{
authorname.Add(item.BookDetails.authorname.ToString());
}
ViewData["AuthorName"] = new SelectList(authorname);
Populate the DropDownList with unique values after they have been already selected from the database. Use the 'distinct' keyword in your SQL query in order to achieve this goal.
SELECT DISTINCT column_name,column_name
FROM table_name;
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);
List<string> authorname = new List<string>();
foreach (string name in DB.Books.Select(x=> new {name = x.authorname}).Distinct())
{
authorname.Add(name);
}
you can directly use linq and get the distinct items ..
code here
list<string> authorNamesDistinct = (from a in DB.Books
select a.BookDetails.authorname).Distinct().ToList();
ViewData["AuthorName"] = new SelectList(authorNamesDistinct);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.