1

I need to update value in each element of a list in C# of VS2013.

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; does not update the value.

Any help would be appreciated.

2 Answers 2

2

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:

for(int p = 0; p < myList.Count; ++p)
{
    decimal? fv = (myList[p].value * 10) / ((decimal?)a_constant);
    givenList[p].value = fv;
}
Sign up to request clarification or add additional context in comments.

5 Comments

You might want to check myList[p] is null first before .value... Cause if it is null you will hit error
@Nic I agree, but without knowing the specific use of this method, it would be difficult to write an error-case which is objectively better than simply hitting the null reference exception :)
Well if i recall correctly you can remove .Value the code still will work and you won't be hitting null reference exception :)
@Nic Depends if it's a Nullable<T> or just an object with a value property (probably the latter since it's lower case)
Anywhere the answer is correct :). The rest is up to him we are just discussing better approach for error handling.
0

tl.ToArray() creates a copy of each element. 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. Your code would update a copy of your element, not the element itself

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.