Editing an item in a list<T>
How do I e开发者_开发知识库dit 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(...));
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() { ... };
}
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 can use the FindIndex() method to find the index of item.
- Create a new list item.
- Override indexed item with the new item.
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;
class1 item = lst[index];
item.foo = bar;
精彩评论