编辑列表<T>中的项目

mah*_*_85 19 .net c# 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(...));
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 44

将项目添加到列表后,您可以通过写入来替换它

list[someIndex] = new MyClass();
Run Code Online (Sandbox Code Playgroud)

您可以通过编写来修改列表中的现有项目

list[someIndex].SomeProperty = someValue;
Run Code Online (Sandbox Code Playgroud)

编辑:你可以写

var index = list.FindIndex(c => c.Number == someTextBox.Text);
list[index] = new SomeClass(...);
Run Code Online (Sandbox Code Playgroud)

  • 列表[someIndex].SomeProperty = someValue; 如果 List&lt;T&gt; 中的 T 定义为结构,则不起作用。 (5认同)

Lee*_*Lee 14

您不需要使用linq,因为List<T>提供了执行此操作的方法:

int index = lst.FindLastIndex(c => c.Number == textBox6.Text);
if(index != -1)
{
    lst[index] = new Class1() { ... };
}
Run Code Online (Sandbox Code Playgroud)


小智 7

public changeAttr(int id)
{
    list.Find(p => p.IdItem == id).FieldToModify = newValueForTheFIeld;
}
Run Code Online (Sandbox Code Playgroud)

附:

  • IdItem是您要修改的元素的id

  • FieldToModify是要更新的项目的字段.

  • NewValueForTheField就是新值.

(它对我来说非常完美,经过测试和实施)

  • 是的,如果您想更新列表元素的公共属性,效果很好。限制是,您不能以这种方式替换整个对象。例如,如果列表是 **`List&lt;String&gt;`** 类型,则赋值不起作用,因为 String 中没有任何属性。在这种情况下,您将需要 `list.FindIndex(lambda)` 并使用 `list[index]=newValue` 来更新它。但它是其他答案的一个很好的补充,在大多数情况下非常方便! (2认同)

Mar*_*cus 6

  1. You can use the FindIndex() method to find the index of item.
  2. Create a new list item.
  3. 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;
Run Code Online (Sandbox Code Playgroud)