General Dictionary - Getting Conversion Error

The following code gives 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 he 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 he trying to perform this conversion? Can I use a foreach loop for this type of object?

+7
dictionary generics c #
source share
6 answers

It should be:

 foreach (KeyValuePair<string, DirectoryInfo> eachItem in myDirectoryList) 

The dictionary does not contain other dictionaries; it contains key pairs and values.

+16
source share

Dictionary<string, DirectoryInfo>

Implements

IEnumerable<KeyValuePair<string, DirectoryInfo>>

This means that the foreach loop cyclically completes the KeyValuePair<string, DirectoryInfo> objects:

 foreach(KeyValuePair<string, DirectoryInfo> kvp in myDirectoryList) { } 

Also why any of the IEnumerable extension methods will always work with the KeyValuePair object:

 // Get all key/value pairs where the key starts with C:\ myDirectoryList.Where(kvp => kvp.Key.StartsWith("C:\\")); 
+6
source share

Stored items are not a dictionary, but 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) 
+4
source share

you should use:

 Dictionary<string, DirectoryInfo> myDirectoryList = GetDirectoryList(); foreach (KeyValuePair<string, DirectoryInfo> itemPair in myDirectoryList) { //do something } 
+4
source share

I think that many of the above people answered the question of why you get the error, i.e. The dictionary stores KeyValuePairs and does not store dictionaries. To stop small errors like the one you have, I would suggest using the new syntax in your development.

 foreach (var eachItem in myDirectoryList) 

The var type will be inferred from myDirectoryList and you will not run into the same problem. Also, if you decide to change the type myDirectoryList, and the properties in its children are the same, your code will still compile.

+4
source share

By default, you iterate over each element of the dictionary, then you must define a data type that has a wildcard

 KeyValuePair<string, DirectoryInfo> 

not a type of dictator. Correctly:

 foreach (KeyValuePair<string, DirectoryInfo> eachItem in myDirectoryList) 

A dictionary is a generic type, so there is no need for boxing and unpacking.

+1
source share

All Articles