I have the following function:
private string ParseJson(dynamic q)
{
string returnJSON = "[{ \"type\" : \"pie\", \"name\" : \"Campaigns\", \"data\" : [ ";
foreach (var grp in q)
{
double currCount = grp.Count();
if (grp.Key != null)
returnJSON += "['" + grp.Key + "', " + currCount + "],";
else
returnJSON += "['none', " + currCount + "],";
}
returnJSON = returnJSON.Substring(0, returnJSON.Length - 1);
returnJSON += "]}]";
return returnJSON;
}
I call it from methods like this one:
public string GetCampaignData()
{
PaymentModelDataContext db = new PaymentModelDataContext();
var q = from Event in db.TrackingEvents
group Event by Event.campaignID;
return ParseJson(q);
}
I use q for several different queries, all grouping data.
The problem is that the runtime can’t bind a type to q for some reason. Is this a proper use of dynamic? Is there a different way to do this?
The problem is
Count()is an extension method off ofIEnumerable<T>, as such it can’t be called from dynamic (because it’s not a true method of the class).Your variable grp is also dynamic because it results from an expression on dynamic variable q:
Since we can’t call extension methods off of dynamic (again, they aren’t true members of the class), we need to explicitly call the extension method instead off the
Enumerablestatic class. So change your code to:And you’ll see it work properly for the
Count(), if you want to really usedynamic.That said, I do agree with @John’s comment that you should consider changing this to a non-dynamic. Actually, what your method would accept would be an IEnumerable> like so:
You can also make the parameter type non-generic specific to your usage if you like. But this would work with all groupings…