3

I am trying to use .net 4.0 lambda methodology to remove double quotes (") around items in an array. Here is the code I have, however, this does not seem to work.

What am I doing wrong?

string[] sa = new string[] { "\"Hello\"", "\"Goodbye\"", "\"Moshi\"", "\"Adios\"" };

// Trying to replace the 
Array.ForEach(sa, s => s.Replace("\"", "")); // Doesn't remove the quotes surrounding the string "Hello".
foreach(var s in sa)
   Console.WriteLine(s);

This still does not get rid of the " around the items.

3 Answers 3

11

There is no lambda expression that could be plugged into ForEach to accomplish your goal, because the action a lambda could take has no write access to the element, and the string itself is immutable.

What you can do is replacing the whole array, like this:

sa = sa.Select(s => s.Replace("\"", "")).ToArray();

This approach works, because it replaces the entire sa array with a newly created array that is based on sa's elements.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use Linq:

sa = sa.Select(s => s.Replace("\"", "")).ToArray();

OR use for loop:

for (var i = 0; i < sa.Length; i++)
    {
        sa[i] = sa[i].Replace("\"", "");
    }

Comments

-1

The other answers are what you should do if you want a new array out of some processing you perform on it's items.

However, if you don't (need a new array), and want to perform an Action on each item of the array (which is what Array.ForEach does), you could do:

//This is pretty much what your code is trying to do
Array.ForEach(sa, i => Console.WriteLine(i.Replace("\"", "")));

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.