Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't convert List<KeyValuePair<...,...>> to IEnumerable<object>?

Tags:

c#

Getting an InvalidCastException when trying something like this :

IEnumerable<object> test = (IEnumerable<object>)new List<KeyValuePair<string, int>>();

However, this did work:

IEnumerable<object> test = (IEnumerable<object>)new List<Dictionary<string, int>>();

So what's the big difference? Why can a KeyValuePair not be converted to an object?

Update: I should probably point out that this did work:

object test = (object)KeyValuePair<string,string>;
like image 677
Tom van der Woerdt Avatar asked Dec 20 '11 13:12

Tom van der Woerdt


4 Answers

First of all Dictionary is already a collection of KeyValuePairs, therefore the second example is casting the entire Dictionary to an object, not the KeyValuePairs.

Anyway, if you want to use the List, you need to use the Cast method to convert the KeyValuePair structure into an object:

IEnumerable<object> test = (IEnumerable<object>)new List<KeyValuePair<string, int>>().Cast<object>();
like image 36
Strillo Avatar answered Sep 23 '22 18:09

Strillo


That's because KeyValuePair<K,V> is not a class, is a struct. To convert the list to IEnumerable<object> would mean that you have to take each key-value pair and box it:

IEnumerable<object> test = new List<KeyValuePair<string, int>>().Select(k => (object)k).ToList();

As you have to convert each item in the list, you can't do this by simply casting the list itself.

like image 184
Guffa Avatar answered Sep 22 '22 18:09

Guffa


Because it is a struct, and not a class : http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx

like image 28
mathieu Avatar answered Sep 24 '22 18:09

mathieu


A KeyValuePair is a struct and doesn't inherit from class object.

like image 31
Fischermaen Avatar answered Sep 24 '22 18:09

Fischermaen