I have IEnumerable<KeyValuePair<string,string>>, from which I would ideally want an anonymous object that has keys as property names and values as property values.
I tried various selection expressions (none of which even compiled ...) and an approach using ExpandoObject(see below), but without success. Is there a good way to do this? If possible, I would like to avoid unnecessary explicit iteration over the collection (i.e. do it all with some LINQ instruction).
This is what I have tried so far. Hope he also clarifies what I'm trying to do:
var kvps = getProps();
dynamic o = new ExpandoObject();
foreach (var kvp in kvps)
{
o.Add(kvp);
}
This is normal at compile time, but at runtime I get a YSOD that states that "System.Dynamic.ExpandoObject" does not contain a definition of "Add" - I think it works at compile time because it ois dynamic, so the compiler doesn’t can know if a method has been added .Add()to it since it was created. It is strange that on the MSDN page, documenation for ExpandoObject.Add() is listed as one of several "explicitly implemented interface methods."
I don’t need to get this into a dynamic object - I just need to get what has the names and values of the properties according to the keys and values of the key-value pairs.
Update: Well, that’s awkward. Turns out this is also an XY problem.
JSON ASP.NET MVC, Json(data) . , , , data, , :
[
{ Key: 'firstkey', Value: 'FirstValue' },
{ Key: 'secondKey', Value: 'secondValue' }
]
{ firstKey: 'FirstValue', secondKey: 'secondValue' }
-, ExpandoObject - ...