Pau*_*ram 9 c# foreach immediate-window visual-studio-2017
我正在尝试使用Immediate WindowVisual Studio 2017将值写入文件。
我有一个名为 的变量_myItems,其类型为Dictionary<int, Dictionary<int, List<int>>>。
我确实遇到了breakpoint这个变量在范围内的地方。我可以跑
?_myItems
Run Code Online (Sandbox Code Playgroud)
在窗口中,我会得到一个列表,如:
Count = 9
[0]: {[536], System.Collections.Generic.Dictionary`2[System.Int32,System.Collections.Generic.List`1[System.Int32]]]}
[1]... omitted for clearance
... omitted for clearance
... omitted for clearance
[8]... omitted for clearance
Run Code Online (Sandbox Code Playgroud)
为了确保我可以在即时窗口中写入文件,我运行了:
File.WriteAllText("test.txt", "testing purposes");
Run Code Online (Sandbox Code Playgroud)
哪个确实写入了文件,因此我确定我可以从那里写入文件。
然后我尝试了以下方法:
?(foreach (KeyValuePair<int, Dictionary<int, List<int>>> pair in _myItems) { foreach (KeyValuePair<int, List<int>> valuePair in pair.Value) { foreach (int numberToWrite in valuePair.Value) { File.AppendAllText("test.txt",numberToWrite.ToString()); } }})
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误:
错误 CS1525:无效的表达式术语“foreach”
通过四处搜索,我遇到了这个问题,但接受的答案仅表明您可以做到。
如何foreach在立即窗口中运行此循环以将值写入文件。
请注意,我知道我应该在我的代码中这样做,但我不认为我稍后会需要这些值。我只是在检查平均值。当我使用完我编写的应用程序时,我决定使用这些值。鉴于准备值的时间需要数小时和数小时,因此不可能停止执行并在代码中重新编写我需要的内容并再次完成整个过程。
我也知道我可以跑
?_myItems[536][0]
Run Code Online (Sandbox Code Playgroud)
然后在文件中手动复制值。这个过程也需要很长时间,因为有很多列表,我想避免它。
有没有可能在直接窗口中进行这项工作?
更新:
我按照答案中的建议做了:
_myItems.Select(x => x.Value)
.ToList()
.ForEach(pair => pair
.ToList()
.ForEach(valuePair => valuePair
.Value
.ForEach(numberToWrite => File.AppendAllText("test.txt", numberToWrite.ToString()))))
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
方法 System.Collections.Generic.List`1[System.Collections.Generic.Dictionary`2[System.Int32,System.Collections.Generic.List`1[System.Int32]]].ForEach() 调用本地方法的评估方法 Microsoft.Win32.Win32Native.GetFullPathName()。不支持在此上下文中评估本机方法。
我什至试图只是Debug.Print我的价值观,例如:
_myItems.ToList().ForEach(pair => System.Diagnostics.Debug.Print(pair.Key));
Run Code Online (Sandbox Code Playgroud)
我最终得到了上面同样的错误。这次调用原生方法报错:
System.Diagnostics.Debugger.IsLogging()
我搜索了这个错误,根据这个答案,建议在调试选项中勾选使用托管兼容模式。但是,这个选项在我的情况下是灰色的,因为我已经处于我假设的调试会话中。
您可以将 foreach 链转换为 linq 表达式:
_myItems.Select(x => x.Value).ToList().ForEach(pair => pair.ForEach(intList => intList.ForEach(numberToWrite => File.AppendAllText("test.txt", numberToWrite.ToString()))));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5964 次 |
| 最近记录: |