【问题标题】:Editing an item in a list<T>编辑列表中的项目<T>
【发布时间】:2011-02-06 17:09:21
【问题描述】:

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

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

【问题讨论】:

  • 你应该为你的文本框命名
  • 也许描述代码的意图会有所帮助。

标签: c# .net generic-list


【解决方案1】:

将一个项目添加到列表后,您可以通过编写替换它

list[someIndex] = new MyClass();

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

list[someIndex].SomeProperty = someValue;

编辑:你可以写

var index = list.FindIndex(c => c.Number == someTextBox.Text);
list[index] = new SomeClass(...);

【讨论】:

  • 列表[someIndex].SomeProperty = someValue;如果 List 中的 T 定义为 struct,则不起作用。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    public changeAttr(int id)
    {
        list.Find(p => p.IdItem == id).FieldToModify = newValueForTheFIeld;
    }
    

    与:

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

    • FieldToModify 是您要更新的项目的字段。

    • NewValueForTheField 就是这样,新值。

    (它非常适合我,经过测试和实施)

    【讨论】:

    • 是的,如果您想更新列表元素的公共属性,可以正常工作。限制是,您不能以这种方式替换整个对象。例如,如果列表的类型为 List&lt;String&gt;,则分配不起作用,因为字符串中没有任何属性。在这种情况下,您需要list.FindIndex(lambda) 并使用list[index]=newValue 来更新它。但这是对其他答案的一个很好的补充,在大多数情况下非常方便!
    【解决方案4】:
    1. 您可以使用 FindIndex() 方法查找项目的索引。
    2. 创建一个新的列表项。
    3. 用新项目覆盖索引项目。

    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;
    

    【讨论】:

      【解决方案5】:
      class1 item = lst[index];
      item.foo = bar;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-17
        • 2021-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-05
        • 2021-12-25
        相关资源
        最近更新 更多