Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count on an IEnumerable<dynamic>

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++;
}
like image 420
Dave Mateer Avatar asked Oct 11 '11 22:10

Dave Mateer


People also ask

Does IEnumerable have count?

IEnumerable has not Count function or property. To get this, you can store count variable (with foreach, for example) or solve using Linq to get count.

How do you measure length of IEnumerable?

If you need to read the number of items in an IEnumerable<T> you have to call the extension method Count , which in general (look at Matthew comment) would internally iterate through the elements of the sequence and it will return you the number of items in the sequence. There isn't any other more immediate way.


2 Answers

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

int count = Enumerable.Count(queryFromMassiveDynamic);
like image 120
Jeff Mercado Avatar answered Sep 30 '22 12:09

Jeff Mercado


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();
like image 23
sehe Avatar answered Sep 30 '22 12:09

sehe