Generic Dictionary - Getting Conversion Error
The following code is giving me an error:
// GetDirectoryList() returns Dictionary<string, DirectoryInfo>
Dictionary<string, DirectoryInfo> myDirectoryList = GetDirectoryList();
// The following line gives a co开发者_JAVA技巧mpile 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:\\"));
The items stored is not a dictionary, but a KeyValuePair:
// GetDirectoryList() returns Dictionary<string, DirectoryInfo>
Dictionary<string, DirectoryInfo> myDirectoryList = GetDirectoryList();
// The following line gives a compile error
foreach (KeyValuePair<string, DirectoryInfo> eachItem in myDirectoryList)
you must use:
Dictionary<string, DirectoryInfo> myDirectoryList = GetDirectoryList();
foreach (KeyValuePair<string, DirectoryInfo> itemPair in myDirectoryList) {
//do something
}
I think that many of the people above have answered the question as to why you are getting the error i.e. The Dictionary stores KeyValuePairs and doesn't store Dictionarys. In order to stop little errors like the one you are having I would suggest using a new syntax in your development.
foreach (var eachItem in myDirectoryList)
The type of var will be inferred from myDirectoryList and you won't run into the same issue. Also if you decide to change the type of myDirectoryList and the properties in its children elements are the same your code will still compile.
By foreach you iterate each item of dictionary, then you should define datatype of which the dictonary hold that is
KeyValuePair<string, DirectoryInfo>
rather than the type of dictonary. So correct way :
foreach (KeyValuePair<string, DirectoryInfo> eachItem in myDirectoryList)
Dictionary is a generic type so no need of boxing and unboxing.
精彩评论