Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 824
Rodney Hickman Avatar asked Jun 08 '11 21:06

Rodney Hickman


1 Answers

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>.

like image 171
TrueWill Avatar answered Oct 01 '22 17:10

TrueWill