How to access count property of a dynamic type in C# 4.0?

Rodney picture Rodney · Jun 8, 2011 · Viewed 18.3k times · Source

I have the follow method that returns a dynamic object representing an IEnumerable<'a> ('a=anonymous type) :

    public dynamic GetReportFilesbyStoreProductID(int StoreProductID)
    {
        Report report = this.repository.GetReportByStoreProductID(StoreProductID);

        if (report == null || report.ReportFiles == null)
        {
            return null;
        }

        var query = from x in report.ReportFiles
                    orderby x.DisplayOrder
                    select new { ID = x.RptFileID, Description = x.LinkDescription, File = x.LinkPath, GroupDescription = x.ReportFileGroup.Description };

        return query;
    }

I want to be able to access the Count property of this IEnumerable anonymous type. I'm trying to access the above method using the following code and it is failing:

        dynamic Segments = Top20Controller.GetReportFilesbyStoreProductID(StoreProductID");

        if (Segments.Count == 0)  // <== Fails because object doesn't contain count.
        {
            ...
        }
  • How does dynamic keyword operate?
  • How can I access the Count property of the IEnumerable anonymous type?
  • Is there a way I can use this anonymous type or do I have to create a custom object so that I can pass back a strongly-typed IEnumerable<myObject> instead of dynamic?

I'd prefer to not do that if I can as this method is only called in one place and creating a throw-away object seems like overkill.

Answer

TrueWill picture TrueWill · Jun 9, 2011

You'll need to explicitly call Enumerable.Count().

IEnumerable<string> segments =
  from x in new List<string> { "one", "two" } select x;

Console.WriteLine(segments.Count());  // works

dynamic dSegments = segments;

// Console.WriteLine(dSegments.Count());  // fails

Console.WriteLine(Enumerable.Count(dSegments));  // works

See Extension method and dynamic object in c# for a discussion of why extension methods aren't supported by dynamic typing.

(The "d" prefix is just for the example code - please do not use Hungarian notation!)

Update: Personally I'd go with @Magnus's answer of using if (!Segments.Any()) and return IEnumerable<dynamic>.