![](/img/trans.png)
[英]How can I run Generic Find method from a List on the Visual Studio Immediate Window?
[英]How can I run a foreach loop in the immediate window of visual studio?
我试图使用Visual Studio 2017中的Immediate Window
将值写入文件。
我有一个名为_myItems
的变量,其类型为Dictionary<int, Dictionary<int, List<int>>>
。
我确实遇到了这个变量在范围内的breakpoint
。 我可以跑
?_myItems
在窗口中,我会得到一个列表:
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
为了确保我可以在即时窗口中编写文件,我运行:
File.WriteAllText("test.txt", "testing purposes");
哪个写了文件,因此我确信我可以从那里写一个文件。
然后我尝试了以下内容:
?(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()); } }})
但是我收到以下错误:
错误CS1525:无效的表达式术语'foreach'
通过搜索我遇到了这个问题,但接受的答案只表明你可以做到这一点。
如何在立即窗口中运行此foreach
循环以将值写入文件。
请注意,我知道我应该在我的代码中完成它,但我不认为我稍后会需要这些值。 我只是检查平均值。 当我完成使用我编写的应用程序时,我决定使用这些值。 鉴于准备值的时间需要数小时和数小时,因此不可能只停止执行并在代码中重新编写我需要的内容并再次完成整个过程。
我也知道我可以跑了
?_myItems[536][0]
然后在文件中手动复制值。 这个过程也需要很长时间,因为有很多列表,我想避免它。
是否有可能在即时窗口中完成这项工作?
更新 :
我按答案中的建议做了:
_myItems.Select(x => x.Value)
.ToList()
.ForEach(pair => pair
.ToList()
.ForEach(valuePair => valuePair
.Value
.ForEach(numberToWrite => File.AppendAllText("test.txt", numberToWrite.ToString()))))
我收到以下错误:
评估方法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));
我最终得到了同样的错误。 这次调用本机方法时出错:
System.Diagnostics.Debugger.IsLogging()
我搜索了这个错误,根据这个答案 ,我们建议从调试选项中勾选Use Managed Compatibility Mode 。 但是,这个选项在我的情况下是灰色的,因为我已经在我假设的调试会话中。
您可以将foreach链转换为linq表达式:
_myItems.Select(x => x.Value).ToList().ForEach(pair => pair.ForEach(intList => intList.ForEach(numberToWrite => File.AppendAllText("test.txt", numberToWrite.ToString()))));
由于.ForEach
不存在于Dictionary<TKey, TValue>
类型上,它只存在于List<T>
类中。
或者,您可以选择字典的值,将其转换为列表并遍历每个值并将其写入文件。
添加到Helio Santos我想补充一下:
_myItems.Select(x => x.Value).ToList().ForEach(pair => pair.ForEach(intList => intList.ForEach(numberToWrite => File.AppendAllText("test.txt", numberToWrite.ToString()))));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.