C# 编辑列表中的项目<;T>;
如何编辑下面代码中列表中的项目:C# 编辑列表中的项目<;T>;,c#,.net,generic-list,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
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(...));
List List=新列表();
整数计数=0,索引=1;
foreach(列表中的1类s)
{
如果(s.Number==textBox6.Text)
index=count;//我找到了一个匹配项,希望在此索引处编辑该项
计数++;
}
列表。删除(索引);
插入(索引,新类别1(…);
将项目添加到列表后,您可以通过编写
list[someIndex] = new MyClass();
list[someIndex].SomeProperty = someValue;
您可以通过写入来修改列表中的现有项
list[someIndex] = new MyClass();
list[someIndex].SomeProperty = someValue;
编辑:您可以编写
var index = list.FindIndex(c => c.Number == someTextBox.Text);
list[index] = new SomeClass(...);
您不需要使用linq,因为
List
提供了执行此操作的方法:
int index = lst.FindLastIndex(c => c.Number == textBox6.Text);
if(index != -1)
{
lst[index] = new Class1() { ... };
}
与:
- IdItem是要修改的元素的id
- FieldToModify是要更新的项目的字段
- NewValueForTheField就是这个新值
List List=新列表();
int index=list.FindIndex(item=>item.Number==textBox6.Text);
Class1 newItem=newclass1();
newItem.Prob1=“SomeValue”;
列表[索引]=新项;
您应该命名文本框。描述代码的意图可能会有所帮助。是的,如果您想更新列表中某个元素的公共属性,可以这样做。限制是,不能以这种方式替换整个对象。例如,如果列表的类型为list
,则赋值不起作用,因为字符串中没有任何属性。在这种情况下,您需要list.FindIndex(lambda)
并使用list[index]=newValue
来更新它。但它是对其他答案的一个很好的补充,在大多数情况下非常方便!列表[someIndex].SomeProperty=someValue;如果列表中的T被定义为struct,则不起作用。
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;