简体   繁体   中英

Why do I get a Unable to cast object of type 'WhereSelectEnumerableIterator for the following code?

I get an 'Unable to cast object of type 'WhereSelectEnumerableIterator'' when I try to convert one Dictionary type to another from within a Select. I don't see any obvious reasons. Please help.

void Main()
{
    Dictionary<string,Dictionary<string,string>> test = new Dictionary<string,Dictionary<string,string>>(); 
    Dictionary<string,string> inner = new Dictionary<string,string>();

    for(int n = 0; n< 10; n++)
    {
        var data = n.ToString();
        inner[data] = data;
    }

    for(int n2 = 0; n2 < 10; n2++)
    {
        test[Guid.NewGuid().ToString()] = inner;
    }


    // test conversion 
    var output = (Dictionary<Guid,Dictionary<string,string>>) test.Select(x => new KeyValuePair<Guid, Dictionary<string,string>>(new Guid(x.Key), x.Value));
}

You have an IEnumerable<Guid,Dictionary<string,string>> . You apparently want a Dictionary<Guid,Dictionary<string,string>> . When you try to assign one to the other, you get a compile time error telling you that your IEnumerable isn't a Dictionary , it's just an IEnumerable . You provided a cast, which is a way of saying, "Sorry compiler, but you're wrong, I know better than you; this IEnumerable is in fact a dictionary, under the hood." Sadly, this is not the case here. You didn't actually have a Dictionary , you had a WhereSelectEnumerableIterator , which isn't a Dictionary .

There are any number of ways you have of creating a dictionary, one of which is to use ToDictionary :

var output = test.ToDictionary(x => new Guid(x.Key), x => x.Value);

On an unrelated note, you've created just one inner dictionary, and set it as the value of every single key you create. You might be under the impression that you've copied this dictionary 10 times. You have not. There only ever is one Dictionary<string, string> here; you just have 10 different GUIDs all pointing to that one dictionary. You'll need to create a bunch of different dictionaries if you want these keys to actually point to different dictionaries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM