Count objects within dynamic anonymous object (C#)

Alex picture Alex · Nov 29, 2012 · Viewed 11.8k times · Source

I have a dynamic object (it's actually json) that I pass into my MVC WebApi controller.

The json object contains multiple lists within an anonymous object that are submitted to the controller from another application via client.PostAsJsonAsync("myapiurl", objectGraph).

What I need to do to validate the object on the MVC side, is to get the count of objects in each list. I can access the lists dynamically via mydynamicobject.mylist and individual items via mydynamicobject.mylist[index] but I can't seem to be able to get a count of mydynamicobject.mylist.

What I've tried so far:

  • LINQ extension methods - doesn't work on dynamic
  • Enumerable.Count(mydynamicobject.mylist) - can't infer type

Any other ideas? The count is actually correctly available in the dynamic object's base but obviously not accessible as a property. Help!

This works now:

// This is a MVC/WebApi method
public dynamic Post(dynamic mydynamicobject)

if (((ICollection)mydynamicobject.mylist).Count == 0)
{
// do something
}

The code that sends the dynamic object (different app):

HttpClient client = new HttpClient();  
client.DefaultRequestHeaders.Accept.Add
  (new MediaTypeWithQualityHeaderValue("application/json")); 

var objectGraph = new { mylist = new { Id = 1 }, mylist2 = new { Name = "ABC" } }; 
var r = client.PostAsJsonAsync("api/mycontroller", objectGraph).Result;

Answer

Chris Pfohl picture Chris Pfohl · Nov 29, 2012

If they are arrays, I believe you're looking for their Length property.

mydynamicobject.mylist.Length

Alternatively, I think you might be able to get away with casting mydynamicobject.mylist to an IEnumerable and then hand it to IEnueramble.Count like so:

IEnumerable.Count((IEnumerable)mydynamicobject.mylist);

you could also do as Paolo mentioned:

((ICollection)mydynamicobject.mylist).Count

Although I can't take credit for that one.