我只是习惯使用lambdas和所有这些好东西。但是,我不知道在这种情况下我需要提供什么参数。
我正在尝试修改I string以使用它的值替换字典中的条目的所有实例,没有什么太花哨,我可以使用简单的foreach
循环执行此操作但我正在尝试将其用作学习练习。
到目前为止我的代码如下:
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]));
}
但是,我收到此错误:There is no argument given that corresponds to the required formal parameter 'action' of 'Array.ForEach<T>(T[], Action<T>)'
。在我看来,我以lambda
表达式的形式提供动作,但我不知道为什么它想要另一个数组或我应该给它的数组。
我尝试过提供null
,string[]
和new [] {typeof(string)}
,但这些只会导致更多错误。
我可以使用这种结构进行此操作,还是仅仅使用传统的foreach
循环更实用?
答案 0 :(得分:2)
这似乎是对.ForEach()
方法的错误使用,它是static
类的Array
方法,而不是扩展方法。有两种方法可以正确执行此操作:
首先,使用Array.ForEach()静态方法并将数组作为第一个参数提供:
Array.ForEach(constants,constant => maskedString = maskedString.Replace(constant, Constants[constant]));
其次,首先将数组转换为List<T>
:
constants.ToList().ForEach(constant => maskedString = maskedString.Replace(constant, Constants[constant]));
第二种方法不会修改原始数组,因此如果需要,您必须执行myArray = myArray.ToList().ForEach().ToArray()
。谢谢克里斯这一点。
答案 1 :(得分:1)
任何时候你最好使用聚合函数:
maskedString = constants.Aggregate(maskedString, (current, constant ) => current.Replace(constant , Constants[constant]));