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)
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<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)
| 归档时间: |
|
| 查看次数: |
94801 次 |
| 最近记录: |