1

Today I got stuck at one point where I need to convert a Dictionary<String,String> to an anonymous object. Is there any one who has tried this before. Below is the example what I actually need.

var dict = new Dictionary<string, object> 
{
    { "CourseId", "XDX123BH" }, 
    { "PersonID", "JIHJ98KH" } 
};

Though this object I want to create is an anonymous object like:

new {CourseID = "XDX123BH", PersonId = "JIHJ98KH" }

Is it possible to do this?

DavidG
  • 113,891
  • 12
  • 217
  • 223
Himanshu Jain
  • 518
  • 4
  • 20
  • Why anonymous objects? What is your source data? – DavidG Oct 30 '15 at 12:32
  • 2
    Since you tagged your question with `ExpandoObject`, you already know about it. Have you tried it, and what did/did not work? – Heinzi Oct 30 '15 at 12:32
  • Sounds like an XY problem to me. How do you want to use the result? Why do you need to use an anonymous class? – Pieter Witvoet Oct 30 '15 at 12:38
  • Yes I have tried it but it needs another library called Microsoft.CSharp.RuntimeBinder.Binder and to include this into the project we need a Nuget version of 3.0 or above but In VS 2012 the latest version is 2.8. So I am unable to add it. So I am searching for some alternative. – Himanshu Jain Oct 30 '15 at 12:38
  • You can update your nuget verson. – Waqar Ahmed Oct 30 '15 at 12:39
  • 2
    Here's some code on Github that does what you're asking: https://gist.github.com/theburningmonk/2221646 – Jason W Oct 30 '15 at 12:39
  • @WaqarAhmed It is showing me that I am already having a latest version of Nuget. Even I explicitly download it from Nuget official website but It is not installing the set up. – Himanshu Jain Oct 30 '15 at 12:43
  • @JasonW It is giving me a compile time error of ToExpando() not defined. I think I am using old version of DLLs. I am using 4.0.0.0 version of IDictionary. – Himanshu Jain Oct 30 '15 at 12:45

1 Answers1

-1

You've your dictionary as

var input = new object();
var input2 = new object();

  var dict = new Dictionary<int, course<T1, T2>>
  {
    {1, new course<T1, T2> {CourseID =(T1)Convert.ChangeType(input, typeof(T1)),
                            PersonID = (T2)Convert.ChangeType(input2, typeof(T2))}}
  };

You've a class as course

public class course<T1, T2>
{
   public T1 CourseID { get; set; }
   public T2 PersonID { get; set; }
}

Updated, this way you can pass everything into it. Parsing your input to the specific type.

Christoph K
  • 344
  • 6
  • 16
  • Hey Christoph... My Dictionary is not predictable It varies from condition to condition.. meaning value can be any thing. You can say I want to pass dynamic parameter in a function. – Himanshu Jain Oct 30 '15 at 12:46
  • Updated, give it a look. Maybe this is a bit of a push for you, to get to the solution. – Christoph K Oct 30 '15 at 12:56