The following code is giving me an error:
// GetDirectoryList() returns Dictionary<string, DirectoryInfo>
Dictionary<string, DirectoryInfo> myDirectoryList = GetDirectoryList();
// The following line gives a compile error
foreach (Dictionary<string, DirectoryInfo> eachItem in myDirectoryList)
The error it gives is as follows:
Cannot convert type 'System.Collections.Generic.KeyValuePair<string,System.IO.DirectoryInfo>' to 'System.Collections.Generic.Dictionary<string,System.IO.DirectoryInfo>’
My question is: why is it trying to perform this conversion? Can I not use a foreach loop on this type of object?
It should be:
foreach (KeyValuePair<string, DirectoryInfo> eachItem in myDirectoryList)
The dictionary doesn't contain other dictionaries, it contains pairs of keys and values.
Dictionary<string, DirectoryInfo>
Implements
IEnumerable<KeyValuePair<string, DirectoryInfo>>
Which means that the foreach loop is looping over KeyValuePair<string, DirectoryInfo>
objects:
foreach(KeyValuePair<string, DirectoryInfo> kvp in myDirectoryList)
{
}
It's also why any of the IEnumerable extension methods will always work with a KeyValuePair object as well:
// Get all key/value pairs where the key starts with C:\
myDirectoryList.Where(kvp => kvp.Key.StartsWith("C:\\"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With