views:

292

answers:

3

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?

+2  A: 

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.

Andrew Hare
I think the OP wants the property's name (and how it's accessed from the item) to be dynamic.
Jon Skeet
I could be wrong though, hence I've deleted my answer. The question is extremely unclear.
Jon Skeet
You make a good point - I read it differently but the question is quite unclear so it is hard to say.
Andrew Hare
I've added clarifications.
Rio
But it still assumes that I know the ``name'' in name = item.Key
Rio
Yes it does - I am unsure of why you wouldn't know the name of the property you want to create.
Andrew Hare
A: 

It sounds like you just want to get the values from a dictionary? If so, MyDictionary.Values should do the trick for you.

Chris
A: 

If you want to construct, somewhere else, another anonymous object, that is type-compatible with the one you generate from your IEnumerable<Item>, you can do that by ensuring that the anonymous type you construct has:

  1. The same number of members
  2. Members with the same type
  3. Members with the same name
  4. ... in the same order

If you do that, they will map to the same single generated type.

Now, why you would want to do that is beyond me, so I'm pretty sure I didn't understand your question. You should post more information about what you want to do.

Anyway, here's the code to produce an anonymous object that is type-compatible with the one from your IEnumerable:

var x = new
{
    name = dict["name"],
    value = dict["value"]
};

Since this obeys all the rules above, it will be of the same type as your objects generated from your Linq query.

Lasse V. Karlsen