编辑列表<t> </t>中的项目

时间:2011-02-06 17:09:21

标签: c# .net generic-list

如何在下面的代码中编辑列表中的项目:

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(...));

5 个答案:

答案 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)

  1. 您可以使用FindIndex()方法查找项目索引。
  2. 创建新的列表项。
  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;