The short story: I want to convert a list/dictionary into an anonymous object
Basically what I had before was:
var model = from item in IEnumerable<Item>
select new
{
name = item.Name
value = item.Value
}
etc.
If I have name, item.Name in a list or dictionary, how can I go about creating the same anonymous object model?
Edit: Clarification:
If the dictionary contains [name, item.Name] and [value, item.Value] as Key Value pairs, how would I go about creating the model without assuming that you know neither name nor value?
Since a
List<T>implementsIEnumerable<T>your existing code should work exactly the same way:For a
Dictionary<TKey,TValue>you could simply do this:This works because
Dictionary<TKey,TValue>implementsIEnumerable<KeyValuePair<TKey,TValue>>so in the second expressionitemwill be typed asKeyValuePair<TKey,TValue>which means you can project a new type usingitem.Keyanditem.Value.