Prevent adding duplicate items to ListBox

I have this code to add selected items from one ListBox to another. How can I prevent a user from adding an item twice? I want ListBox be added to lstBoxToUserProjects to contain only individual items without duplicate entries.

 protected void btnAddSelectedItem_Click(object sender, EventArgs e) { List<ListItem> itemsToAdd= new List<ListItem>(); foreach (ListItem listItem in lstbxFromUserProjects.Items) { if (listItem.Selected) itemsToAdd.Add(listItem); } foreach (ListItem listItem in itemsToAdd) { lstBoxToUserProjects.Items.Add(listItem); } } 

EDIT: This is what I ended up using

 protected void btnAddSelectedItem_Click(object sender, EventArgs e) { List<ListItem> itemsToAdd= new List<ListItem>(); foreach (ListItem listItem in lstbxFromUserProjects.Items) { if (listItem.Selected) itemsToAdd.Add(listItem); } foreach (ListItem listItem in itemsToAdd) { if (!lstBoxToUserProjects.Items.Contains(listItem)) { lstBoxToUserProjects.Items.Add(listItem); } } } 
+6
source share
5 answers

If you bind the lstBoxToUserProjects list to a data source (HashSet), you can do a simple check to see if the item proposed for selection was already at the destination:

 foreach(ListItem itemToAdd in itemsToAdd) { if (selectedItems.Contains(itemToAdd)) continue; lstBoxToUserProjects.Items.Add(itemToAdd); } 

Note. I suggest a HashSet, because then you can do a run check on the set, while a list needs to be listed to check for consistency.

+4
source

You should simply call ListBox.Items.Contains () in the if statement to check if it is added.

 foreach (ListItem listItem in itemsToAdd) { if (!lstBoxToUserProjects.Items.Contains(listItem)) { lstBoxToUserProjects.Items.Add(listItem); } } 
+3
source

Try the following:

 protected void btnAddSelectedItem_Click(object sender, EventArgs e) { lstBoxToUserProjects.Items.AddRange(lstbxFromUserProjects.Items.Where(li => !lstBoxToUserProjects.Items.Contains(li)).ToArray()); } 

That assumes C # 3.5, at least.

+2
source

Change itemsToAdd from List to HashSet :

 HashSet<ListItem> itemsToAdd= new HashSet<ListItem>(); ... itemsToAdd.Add(listItem) // Adds only new items. 

Add MSDN :

Return value

Type: System.Boolean true if the item is added to a HashSet (Of T) object; false if the item is already present. (gdoron- and without inserting the element again ...)

0
source

Using

 _items_Unique = _items.Distinct().ToList(); 

quickly, then comparing where _items_Unique and _items are two lists

 List<string> _items_Unique = new List<string>(); List<string> _items = new List<string>(); 
0
source

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


All Articles