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.


    The IEnumerable<T> that's returned from that method doesn't have a Count property, so I don't know what you're talking about. Maybe you forgot to write ToList() on the end to reify it into a list, or you meant to call the Count() method on IEnumerable<T> ?


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


    Count() needs to enumerate to complete collection, you probably want:

    if (!Segments.Any()) 
    {
    }
    

    And your function should return IEnumerable<object> instead of dynamic

    链接地址: http://www.djcxy.com/p/31894.html

    上一篇: 按BACK按钮时,setResult不起作用

    下一篇: 如何在C#4.0中访问动态类型的count属性?