James Hughes James Hughes - 15 days ago 8
C# Question

T[] parameter in string[].Foreach()

I'm just getting used to using lambdas and all of that good stuff. However, I am not aware of what argument I need to provide in this case.

I am attempting to modify I string to replace all instances of an entry in a dictionary with it's value, nothing too fancy, I could do this with a simple

foreach
loop but I'm trying to use this as a learning exercise.

My code so far is as follows:

string maskString = Masks[alias];
Regex regex = new Regex(@"({[\w+|\d]+})");
MatchCollection matches = regex.Matches(maskString);
string[] constants = matches.Cast<Match>().Select(m => m.Value).ToArray();
string maskedString = "";
if (constants.All(constant => Constants.ContainsKey(constant)))
{
constants.ForEach(constant => maskedString = maskedString.Replace(constant, Constants[constant]));
}


However, I am receiving this error:
There is no argument given that corresponds to the required formal parameter 'action' of 'Array.ForEach<T>(T[], Action<T>)'
. It seems to me that I am providing the action in the form of a
lambda
expression, but I have no idea why it wants another array or what array I should give it.

I have tried providing it with
null
,
string[]
and
new [] {typeof(string)}
but these just cause more errors.

Is it possible for me to conduct this operation using this structure or would it be more practical just to use a traditional
foreach
loop?

Answer

Anytime you would better use Aggregate function:

maskedString = constants.Aggregate(maskedString, (current, constant ) => current.Replace(constant , Constants[constant]));