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(...));
This question is related to
c#
.net
generic-list
public changeAttr(int id)
{
list.Find(p => p.IdItem == id).FieldToModify = newValueForTheFIeld;
}
With:
IdItem is the id of the element you want to modify
FieldToModify is the Field of the item that you want to update.
NewValueForTheField is exactly that, the new value.
(It works perfect for me, tested and implemented)
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() { ... };
}
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(...);
class1 item = lst[index];
item.foo = bar;
List<Class1> list = new List<Class1>();
int index = list.FindIndex(item => item.Number == textBox6.Text);
Class1 newItem = new Class1();
newItem.Prob1 = "SomeValue";
list[index] = newItem;
Source: Stackoverflow.com