How to check if a value exists in a list box before adding to asp.net

how can I check if a value is in the list to avoid duplicates?

I added some values ​​to the server block columns, and when I add to the list, I get more duplicates.

How to avoid duplicates?

lst_Viewers.Items.Add(reader["Name"].ToString()); 
+4
source share
3 answers
 ListItem item = new ListItem(reader["Name"].ToString()); if ( ! lst_Viewers.Items.Contains(item) ){ lst_Viewers.Items.Add(item); } 

or

 var name = reader["Name"].ToString(); ListItem item = lst_Viewers.Items.FindByText(name); if ( item == null ){ lst_Viewers.Items.Add(new ListItem(name)); } 
+7
source
 if(!lst_Viewers.Items.Any(item => item.Value.ToString().Equals(reader["Name"].ToString()) lst_Viewers.Items.Add(reader["Name"].ToString()); 
+1
source

Another approach could be to insert all the values ​​into a List<string> and then add the elements only after the loop, using .Distinct() to get only unique values:

 List<string> names = new List<string>(); while (reader.Read()) names.Add(reader["Name"].ToString()) names.Distinct().ToList().ForEach(name => lst_Viewers.Items.Add(name)); 

This way, you don’t have to look for the whole DropDown at each iteration - more elegant (in my opinion) and more efficient.

+1
source

Source: https://habr.com/ru/post/1396376/


All Articles