下面的方法返回表示IEnumerable<'a> ('a=anonymous类型)的动态对象:
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;
}我希望能够访问这个匿名类型的Count属性。我试图使用以下代码访问上述方法,但它失败了:
dynamic Segments = Top20Controller.GetReportFilesbyStoreProductID(StoreProductID");
if (Segments.Count == 0) // <== Fails because object doesn't contain count.
{
...
}IEnumerable匿名类型的Count属性?IEnumerable<myObject>而不是dynamic?H 216f 217如果可以的话,我宁愿不要这样做,因为这个方法只在一个地方调用,而创建一个丢弃对象似乎是过火了。
发布于 2011-06-08 22:09:41
您需要显式地调用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有关为什么动态类型不支持扩展方法的讨论,请参见Extension method and dynamic object in c#。
( "d“前缀只是示例代码的前缀--请不要使用匈牙利符号!)
更新:就我个人而言,我将使用使用if (!Segments.Any())的@Magnus's answer并返回IEnumerable<dynamic>。
https://stackoverflow.com/questions/6285575
复制相似问题