Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 309
Paul Michaels Avatar asked Jun 17 '10 13:06

Paul Michaels


2 Answers

It should be:

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

The dictionary doesn't contain other dictionaries, it contains pairs of keys and values.

like image 150
Hans Olsson Avatar answered Sep 21 '22 15:09

Hans Olsson


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:\\"));
like image 37
Justin Niessner Avatar answered Sep 22 '22 15:09

Justin Niessner