4

I am attempting to create a function that converts an anonymous type to a dictionary. I was going over the accepted answer in this link thread. However I am getting the error

Cannot use lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type

This is what I am trying to do

public Dictionary<string,string> convert(dynamic dtype)
{
 var props = content.GetType().GetProperties();
 var pairs = props.Select(x => x.Name + "=" + x.GetValue(a, null)).ToArray();  // <----Exception
 var result = string.Join("&", pairs);
 return result
} 

Any suggestion on how I can fix this ? I am trying to do this

       var student= new
        {
            // TODO: Make this figure out and return underlying device status.
            type = "Active",
        };



 var dict = convert(student);
Ahmad Karimi
  • 1,285
  • 2
  • 15
  • 26
MistyD
  • 16,373
  • 40
  • 138
  • 240

1 Answers1

4

exception is here :

 x.GetValue(a, null)

just change a to content like this :

var pairs = props.Select(x => x.Name + "=" + x.GetValue(content, null)).ToArray();

content is name of your anonymous object .

But this solution you wrote not return dictionary . if you want dictionary do this :

public static Dictionary<string, string> convert(object content)
        {

            var props = content.GetType().GetProperties();
            var pairDictionary = props.ToDictionary(x => x.Name,x=>x.GetValue(content,null)?.ToString());
            return pairDictionary;
        }
masoud
  • 355
  • 2
  • 10