C# Lambda Expression To Replace String Values In String Array

  • A+

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.


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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: