Convert KeyValuePair collection to anonymous type

Is it possible to convert a IEnumerable<KeyValuePair<string,string>>KeyValuePair to an anonymous type?

Dictionary<string, string> dict= new Dictionary<string, string>();
dict.add("first", "hello");
dict.add("second", "world");

var anonType = new{dict.Keys[0] = dict[0], dict.Keys[1] = dict[1]};

Console.WriteLine(anonType.first);
Console.WriteLine(anonType.second);

********************output*****************
hello
world

The reason I would like to do this is because I am retrieving an object from a web service representing an object that does not exist in wsdl. The returned object contains only the KeyValuePair collection containing custom fields and their values. These custom fields can be called anything, so I can't really map the xml deserialization method to the final object that I will use (whose properties must be bound to the grid).

* Just because I used Dictionary<string,string>it does not mean that it is absolutely a dictionary, I just used it to illustrate. Indeed hisIEnumerable<KeyValuePair<string,string>>

, , . #.NET 4.0.

0
3
+6

, , .

, , - :

public class MyDictionary<T,K> : Dictionary<string,string> // T and K is your own type
{
    public override bool TryGetValue(T key, out K value)
    {
        string theValue = null;
        // magic conversion of T to a string here
        base.TryGetValue(theConvertedOfjectOfTypeT, out theValue);
        // Do some magic conversion here to make it a K, instead of a string here
        return theConvertedObjectOfTypeK;
    }
}
0

ExpandoObject is the best option, which I believe is a wrapper around some XML. You can also use XElement:

var result = new XElement("root");
result.Add(new XElement("first", "hello"));
result.Add(new XElement("second", "world"));

Console.WriteLine(result.Element("first").Value); 
Console.WriteLine(result.Element("second").Value);

foreach (var element in result.Elements())
    Console.WriteLine(element.Name + ": " + element.Value);

I did not use ExpandoObject, so I’ll try it first, because I understand that it does exactly what you want, as well as something new and interesting to learn.

0
source

All Articles