How to remove the element from List in C#?

14,895

Solution 1

You are removing items, then advancing i, therefore skipping the item that moved into the previous position that i represented.

e.g.

items = 5 i = 0 -> remove i => items = 4, i = 0

-> i++ => items = 4, i = 1

-> remove i => items= 3, i = 1

-> i++ => items = 3, i = 2

-> remove i => items = 3, i = 2

-> i++ => items = 3, i = 3

-> remove i => index out of range

Solution 2

Your question is unclear, but it sounds like your user interface is bound to the list. If so, you won't see changes because the list doesn't support change notification. You should use a BindingList<T> (for windows forms) or ObservableCollection<T> (for WPF) to get change notification.

Solution 3

This does work.

If there are two List instances in your "temp" list, doing temp.RemoveAt(0); will remove the first of the two lists. It will remove the entire List from temp, not just the first int value in the internal list.

Share:
14,895
user2120901
Author by

user2120901

Updated on June 04, 2022

Comments

  • user2120901
    user2120901 almost 2 years

    I got a liiitle problem.

    There is

    List<List<UInt32>> temp = new List<List<UInt32>>();
    

    For example,

    there are two List<UInt32> records within the List temp however, when i try to do something like temp.removeAt(0); it doesn't remove the first row (List<UInt32>) .. Why is that? Do i do something wrong?

    Update

    Here is the code that doesn't work. I know there are 2 List<UInt32> within the main List and I know that the first List<UInt32>.Count is 1 but when I check the same position after this code, the first code's Count is still one.

                            int i = 0;
                            bool boolA = true;
    
                            while (boolA)
                            {
                                if (temp[i].Count == 1) 
                                {
                                    temp.RemoveAt(i);
                                    temps++; 
                                }
    
                                if (i == temp.Count - 1) boolA = false;
                                i++;