Count on an IEnumerable<dynamic>

百般思念 提交于 2019-12-07 06:19:57

问题


I'm using Rob Conery's Massive ORM.

Is there an elegant way to do a count on the record set returned?

dynamic viewModelExpando = result.ViewData.Model;
var queryFromMassiveDynamic = viewModelExpando.TenTricksNewestFirst;

//fails as have actually got TryInvokeMember on it
var z = queryFromMassiveDynamic.Count();

//works
int i = 0;
foreach (var item in queryFromMassiveDynamic) {
    i++;
}

回答1:


Rather than calling it using the extension method member syntax, try calling the static method directly.

int count = Enumerable.Count(queryFromMassiveDynamic);



回答2:


The question is a bit off. You're not actually doing a count of an IEnumerable<dynamic>. You're trying a count on a dynamic (which hopefully holds an IEnumerable).

The straightforward way to do this is by using a cast:

 var z = (queryFromMassiveDynamic as IEnumerable<dynamic>).Count();



回答3:


You can take sehe's answer, which is to cast the result.

var z = (queryFromMassiveDynamic as IEnumerable<dynamic>).Count();

Instead, realize what you are getting from the Query member function. You are in fact getting an IEnumerable of type dynamic and var has trouble with those.

Change this line

var queryFromMassiveDynamic = viewModelExpando.TenTricksNewestFirst;

To this

IEnumerable<dynamic> queryFromMassiveDynamic = viewModelExpando.TenTricksNewestFirst;

Count will show up without having to do any casting.



来源:https://stackoverflow.com/questions/7733305/count-on-an-ienumerabledynamic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!