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 = "Доллар" } }
Declaring and using an anonymous type objectThe keyword var is used to declare anonymous type objects. The new operator, along with an object initializer, is used to define the value.
Anonymous types in C# are the types which do not have a name or you can say the creation of new types without defining them. It is introduced in C# 3.0. It is a temporary data type which is inferred based on the data that you insert in an object initializer.
Anonymous types are class types that derive directly from object , and that cannot be cast to any type except object . The compiler provides a name for each anonymous type, although your application cannot access it.
Definition and UsageThe lambda keyword is used to create small anonymous functions. A lambda function can take any number of arguments, but can only have one expression. The expression is evaluated and the result is returned.
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 });
As itowlson said, you can't declare such a beast, but you can indeed create one:
static IDictionary<TKey, TValue> NewDictionary<TKey, TValue>(TKey key, TValue value) { return new Dictionary<TKey, TValue>(); } static void Main(string[] args) { var dict = NewDictionary(new {ID = 1}, new { Column = "Dollar", Localized = "Доллар" }); }
It's not clear why you'd actually want to use code like this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With