Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A dictionary where value is an anonymous type in C#

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 = "Доллар" } } 
like image 693
abatishchev Avatar asked Oct 24 '09 23:10

abatishchev


People also ask

How do you declare an anonymous type?

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.

What are anonymous types in C sharp?

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.

What are anonymous data types?

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.

Which keyword is used to create an anonymous?

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.


2 Answers

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 }); 
like image 57
itowlson Avatar answered Sep 19 '22 14:09

itowlson


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.

like image 36
Ðаn Avatar answered Sep 19 '22 14:09

Ðаn