A dictionary where value is an anonymous type in C#

abatishchev picture abatishchev · Oct 25, 2009 · Viewed 34.3k times · Source

Is it possible in C# to create a System.Collections.Generic.Dictionary<TKey, TValue> where TKey is unconditioned class and TValue - an anonymous class with a number of properties, for example - database column name and it's localized name.

Something like this:

new { ID = 1, Name = new { Column = "Dollar", Localized = "Доллар" } }

Answer

itowlson picture itowlson · Oct 25, 2009

You can't declare such a dictionary type directly (there are kludges but these are for entertainment and novelty purposes only), but if your data is coming from an IEnumerable or IQueryable source, you can get one using the LINQ ToDictionary() operator and projecting out the required key and (anonymously typed) value from the sequence elements:

var intToAnon = sourceSequence.ToDictionary(
    e => e.Id,
    e => new { e.Column, e.Localized });