forum

Home / DeveloperSection / Forums / Removing an item from a list c#

Removing an item from a list c#

Anonymous User203428-Sep-2013

I am having trouble with removing an item from a list in c#. My current code is below:

for (int i = current.Count - 1; i >= 0; i--) 
    {
        foreach (ListItem li in sp_list.Items)
        {
            if (li.Text == current[i].uname)
            {
                current.RemoveAt(i);
            }
        }
    }


The aim of the code is to compare the existing items in a list box with newly added items so I know which items have just been added. So currently I am getting the current list box items from the database (they are stored here, it is a databound list box), entering these into a list and for each of the list items, comparing them with the items in a list box and if they match, remove the item from the list.

Therefore, in the end, if I add two new entries, the list should only be storing the two newly added values.

The code does not work as the first item is removed fine, but then, the value of i is greater than current.count - and therefore I get an out of range exception!

Could someone help me with this issue? Apologies about the confusing question, it's hard to explain! Thanks


Updated on 28-Sep-2013
I am a content writter !

Can you answer this question?


Answer

1 Answers

Liked By