Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# anonymous object with properties from dictionary

I'm trying to convert an dictionary to an anonymous type with one property for every Key.

I tried google it but all I could find was how to convert a anonymous object to a dictionary.

My dictionary looks something like this:

var dict = new Dictionary<string, string> {     {"Id", "1"},     {"Title", "My title"},     {"Description", "Blah blah blah"}, }; 

And i would like to return a anonymous object that looks like this.

var o = new  {     Id = "1",     Title = "My title",     Description = "Blah blah blah" }; 

So I would like it to loop thru every keyValuePair in the dictionary and create a property in the object for every key.

I don't know where to begin.

Please help.

like image 572
Verendus Avatar asked Apr 02 '15 13:04

Verendus


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...


1 Answers

You can't, basically. Anonymous types are created by the compiler, so they exist in your assembly with all the property names baked into them. (The property types aren't a problem in this case - as an implementation detail, the compiler creates a generic type and then creates an instance of that using appropriate type arguments.)

You're asking for a type with properties which are determined at execution time - which just doesn't fit with how anonymous types work. You'd have to basically compile code using it at execution time - which would then be a pain as it would be in a different assembly, and anonymous types are internal...

Perhaps you should use ExpandoObject instead? Then anything using dynamic will be able to access the properties as normal.

like image 179
Jon Skeet Avatar answered Sep 25 '22 11:09

Jon Skeet