如何在下面的代码中编辑列表中的项目:
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(...));
答案 0 :(得分:41)
将项目添加到列表后,您可以通过编写
来替换它list[someIndex] = new MyClass();
您可以通过编写
来修改列表中的现有项目list[someIndex].SomeProperty = someValue;
编辑:您可以写
var index = list.FindIndex(c => c.Number == someTextBox.Text);
list[index] = new SomeClass(...);
答案 1 :(得分:14)
您不需要使用linq,因为List<T>
提供了执行此操作的方法:
int index = lst.FindLastIndex(c => c.Number == textBox6.Text);
if(index != -1)
{
lst[index] = new Class1() { ... };
}
答案 2 :(得分:7)
public changeAttr(int id)
{
list.Find(p => p.IdItem == id).FieldToModify = newValueForTheFIeld;
}
使用:
IdItem是您要修改的元素的ID
FieldToModify是您要更新的项目的字段。
NewValueForTheField就是新值。
(它适合我,测试和实施)
答案 3 :(得分:4)
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;
答案 4 :(得分:3)
class1 item = lst[index];
item.foo = bar;