Editing an item in a list<T>

mah_85 picture mah_85 · Feb 6, 2011 · Viewed 120.4k times · Source

How do I edit an item in the list in the code below:

List<Class1> list = new List<Class1>();

int count = 0 , index = -1;
foreach (Class1 s in list)
{
    if (s.Number == textBox6.Text)
        index = count; // I found a match and I want to edit the item at this index
    count++;
}

list.RemoveAt(index);
list.Insert(index, new Class1(...));

Answer

SLaks picture SLaks · Feb 6, 2011

After adding an item to a list, you can replace it by writing

list[someIndex] = new MyClass();

You can modify an existing item in the list by writing

list[someIndex].SomeProperty = someValue;

EDIT: You can write

var index = list.FindIndex(c => c.Number == someTextBox.Text);
list[index] = new SomeClass(...);