Convert KeyValuePair to anonymous type in LINQ query

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(); // returns IEnumerable<KeyValuePair<string,string>>

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, , :

// What I get:
[
   { Key: 'firstkey', Value: 'FirstValue' }, 
   { Key: 'secondKey', Value: 'secondValue' } 
]

// What I want:
{ firstKey: 'FirstValue', secondKey: 'secondValue' }

-, ExpandoObject - ...

+5
3

ExpandoObject IDictionary<string, object> - :

var kvps = getProps();
dynamic o = new ExpandoObject();
var dict = o as IDictionary<string, object>;
foreach (var kvp in kvps)
{
    dict.Add(kvp.Key, kvp.Value);
}

o, :

var example = o.YourKey;

JSON ASP.NET MVC, Json (data) .

.

, ExpandoObject. MVC 3 JSON serializer . , , IEnumerable<KeyValuePair<string, object>> :

var kvps = getProps();
var dictionary = kvps.ToDictionary(k => k.Key, v => v.Value);
return Json(dictionary, JsonRequestBehavior.AllowGet); //take out allow get if you don't need it.

.

+4

ExpandoObject IDictionary<string, object> :

var kvps = getProps(); // returns IEnumerable<KeyValuePair<string,string>>

IDictionary<string, object> o = new ExpandoObject();
foreach (var kvp in kvps)
{
    // Or use Add(kvp.Key, kvp.Value), if you want
    o[kvp.Key] = kvp.Value;
}

dynamic d = o;
// Now you can use the properties
+6

I think you need to give your expando object in an IDictionary and call Add (string, object)

+1
source

All Articles