简体   繁体   English

在VS2013的C#中更新列表中每个元素的值

[英]update value in each element of a list in C# of VS2013

I need to update value in each element of a list in C# of VS2013. 我需要在VS2013的C#中更新列表中每个元素的值。

The code: 编码:

var wl = myList.ToArray();
List<myElement> tl = new List<myElement>();
tl = givenList; // I need to update values in element in this list
for(int p =0; p < wl.Count(); ++p)
{
    decimal? fv = (wl[p].value * 10) / ((decimal?)a_constant);
    tl.ToArray()[p].value = fv; // this cannot update the value
}
myList = tl;

But, the tl.ToArray()[p].value = fv; 但是, tl.ToArray()[p].value = fv; does not update the value. 不更新值。

Any help would be appreciated. 任何帮助,将不胜感激。

You're creating a huge amount of variables which don't really do much, and is very hard to read. 您正在创建大量的变量,这些变量实际上并没有做太多,而且很难读取。 Also, you don't need to keep calling ToArray Try something like this: 另外,您无需继续调用ToArray尝试如下操作:

for(int p = 0; p < myList.Count; ++p)
{
    decimal? fv = (myList[p].value * 10) / ((decimal?)a_constant);
    givenList[p].value = fv;
}

tl.ToArray() creates a copy of each element. tl.ToArray()创建每个元素的副本。 I'm not sure what is the type of myElement in the code, but if it's a struct or any other value type that would explain why your collection is not being modified. 我不确定代码中myElement的类型是什么,但是如果它是struct或任何其他value type ,则可以解释为什么不修改您的集合。 Your code would update a copy of your element, not the element itself 您的代码将更新元素的副本,而不是元素本身

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM