简体   繁体   中英

List to Anonymous Type in c#

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> 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 .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM