Reputation: 17223
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);
Upvotes: 4
Views: 2465
Reputation: 375
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;
}
Upvotes: 6