我有这个:
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()没有在任何地方分配回报值......
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可以工作
不要那样使用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)
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |