11

I'm pretty sure this has worked before in some code I have written, not sure what I am missing here.

The following code does not change the string values in my list. Why?

var items = listBox1.Items.Cast<string>().ToList();
items.ForEach(item => item = (!chkBox1.Checked) ? "move " + item : "move -check " + item);

EDIT : Just to clarify, the list remains the same as when it was created.

EDIT : Apologies, the items list (listBox1.Items) contains alphanumeric strings as follows.

J00123456

J00123344

J00123458

Also, just to confirm, I have successfully done this with a custom list of T (shown below), which is why I thought it would work here.

var tapes = new List<TapeInfo>();
... //Populated list
tapes.ForEach(x => x.vItem = "tapelib 3592 -eject " + x.vItem);  //Works here
6
  • What is the exact error or exception that you are getting here ?
    – Dhrumil
    Commented Apr 28, 2015 at 6:23
  • @HarveySpecter The following code does not change the string
    – Grundy
    Commented Apr 28, 2015 at 6:23
  • 2
    Which string are you comparing with? the listbox items? your ToList is making a copy
    – Sayse
    Commented Apr 28, 2015 at 6:24
  • @HarveySpecter I edited my initial question. No error, just receiving the same result, I expect an altered list.
    – Magic Mick
    Commented Apr 28, 2015 at 6:24
  • I cannot properly answer the question unless I know what is inside Items. Is it just string or something else?
    – Euphoric
    Commented Apr 28, 2015 at 6:29

3 Answers 3

15

You should use the Select function if you want to get a different result.

var items = listBox1.Items.Cast<string>().ToList();
listBox1.Items = items.Select(item => (!chkBox1.Checked) ? "move " + item : "move -check " + item).ToList();

The ForEach function can do something according to a collection value, but can't do it to the values themselves.

The Select function will create a new collection according to the given collection.

Edit

About your edit of successfully changing values by using

tapes.ForEach(x => x.vItem = "tapelib 3592 -eject " + x.vItem);

You need to understand how passing argument by value/reference works.

In c#, when writing var obj1 = new object(), obj1 is a pointer to the new object() that exists on the heap.

When you pass obj1 to a function public void Foo(object obj) { //... } by calling Foo(obj1), the function will get the parameter as new pointer to the same object on the heap.

Therefore, when you use ForeEach on the object itself,

object.ForEach(obj => obj = new object()) // No changed outside the Foreach

only the new pointer will be changed and it will point on a new object but the original pointer isn't changed.

But if you use it on an inner object,

object.ForEach(obj => obj.InnerObject = new object()) // Changed outside the Foreach

this will change the pointed inner object and the inner object will be changed.

1
  • 4
    Just to clarify: foreach can't re-assign the values, but if the value is an object, it can change it's properties. Commented Apr 28, 2015 at 7:01
6

strings are immutable, so they cannot be changed. Assigning another value to that variable only changes that variable (difference between call-by-reference and call-by-value).

When you use the ForEach-method, you actually iterate over your items-list using the item-variable declared in your lambda-expression. Assigning a different value to that variable, cannot change the list.

And to have it clear what my first sentence means: You cannot change the value of your variable, because it's immutable, so you assign the variable, which cannot take affect to the list.

5
  • 1
    While this is true, it is not applicable in this case.
    – Euphoric
    Commented Apr 28, 2015 at 6:22
  • 1
    He assumes, that when he assigns another value to the variable using to iterate over items, he will change the list. So this IS applicable.
    – Patrik
    Commented Apr 28, 2015 at 6:24
  • Thats correct, I just realised this. I have added a code sample (above) where this works with a custom list.
    – Magic Mick
    Commented Apr 28, 2015 at 6:45
  • @MickIlovski A bit less elegant way could have been to use a for-loop and actually changing the list. Could be a tiny bit faster, but with several line of code more.
    – Patrik
    Commented Apr 28, 2015 at 6:55
  • @Euphoric My answer is not simply about the problem, but concerning what I believe the poster actually means/thinks. Finding X instead of solving Y.
    – Patrik
    Commented Apr 28, 2015 at 6:57
4

Foreach simply can't do it, since item is a local variable within the loop's scope.
What you have is basically the same as using the long version:

foreach(string item in listBox1.Items.Cast<string>().ToList())
{
    item = (!chkBox1.Checked) ? "move " + item : "move -check " + item;
}

you can use a for loop to achieve your goal:

string Item;
for(var i=0;i < listBox1.Items.Count; i++)
{
    Item = listBox1.Items[i].ToString(); // Listbox Items are objects, so you need to use ToString() here
    listBox1.Items[i] = (chkBox1.Checked) ? "move -check " + Item : "move " + Item;
}

That's assuming, of course, that the items are and should be strings. I've also improved readability of your ternary condition.

4
  • The reason behind this is that .NET does not allow lambdas to have a ref parameter. Otherwise, a ForEach overload working on IList<T> could easily exist.
    – Georg
    Commented Apr 28, 2015 at 6:41
  • Actually, it can't be done in the long version of foreach as well, so while your statement about ref parameters in lamdba expressions is true, it's not the actual reason why it's not working. Commented Apr 28, 2015 at 6:54
  • 1
    Please do not confuse the language construct foreach and the library method ForEach. They are by no means connected except that they have a similar semantics.
    – Georg
    Commented Apr 28, 2015 at 8:02
  • @Georg Point taken. you're correct, this confusion was my mistake. Commented Apr 28, 2015 at 8:03

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.