Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editing an item in a list<T>

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(...)); 
like image 581
mah_85 Avatar asked Feb 06 '11 17:02

mah_85


People also ask

Can we modify list while iterating C#?

You could only use foreach then, but then it's not possible to modify the list in the loop.


2 Answers

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(...); 
like image 182
SLaks Avatar answered Oct 01 '22 11:10

SLaks


You don't need to use linq since List<T> provides the methods to do this:

int index = lst.FindLastIndex(c => c.Number == textBox6.Text); if(index != -1) {     lst[index] = new Class1() { ... }; } 
like image 40
Lee Avatar answered Oct 01 '22 11:10

Lee