有没有办法做到这一点,在List <T> .ForEach()语句中分配一个值?

Fra*_*rme 2 c# .net-3.5

我有这个:

var lineArray = line.Split(';');

lineArray.ToList().ForEach(x =>
{
    if (x == "(null)")
        x = "NULL";
    else
        x = string.Format("'{0}'", x);
});
Run Code Online (Sandbox Code Playgroud)

这样运行正常,但似乎没有改变其中的元素lineArray.我想把结果分配ForEach给a var但它返回void.

有任何想法吗 ?

编辑:我认为这是因为ToList()没有在任何地方分配回报值......

ASh*_*ASh 7

var lineArray = line.Split(';')
                    .Select(x=>x == "(null)"
                               ? "NULL"
                               : string.Format("'{0}'", x))
                    .ToArray();
Run Code Online (Sandbox Code Playgroud)

你正在尝试使用List<T>.ForEach(Action<T> action)lambda表达式(T是字符串)

如果lambda表达式被命名方法替换,则事实证明只修改了方法参数,但是更改没有反映在调用方,因为x不是ref参数

private void Replace(string x)
{
    if (x == "(null)")
        x = "NULL";
    else
        x = string.Format("'{0}'", x);
}

var list = lineArray.ToList();
list.ForEach(Replace);
// check list here and make sure that there are no changes
Run Code Online (Sandbox Code Playgroud)

如果T是引用类型并且操作修改了某些属性而不是引用本身,则ForEach可以工作


Dan*_*ite 5

不要那样使用ForEach- 使用for循环.

for (int i = 0; i < lineArray.Length; i++)
{
    if (lineArray[i] == "(null)")
        lineArray[i] = "NULL";
    else
        lineArray[i] = string.Format("'{0}'", lineArray[i]);
}
Run Code Online (Sandbox Code Playgroud)