List to Anonymous Type in c#

anonymous-types, c#, dictionary, list

Solution

Since a `List<T>` implements `IEnumerable<T>` your existing code should work exactly the same way:

var model = from item in yourList
            select new { name = item.Name };

For a `Dictionary<TKey,TValue>` you could simply do this:

var model = from item in yourDictionary
            select new {
                name = item.Key
                value = item.Value
            };

This works because `Dictionary<TKey,TValue>` implements `IEnumerable<KeyValuePair<TKey,TValue>>` so in the second expression `item` will be typed as `KeyValuePair<TKey,TValue>` which means you can project a new type using `item.Key` and `item.Value`.

Problem

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`?

Original source