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(...));
You could only use foreach then, but then it's not possible to modify the list in the loop.
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(...);
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() { ... }; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With