Counting records using LINQ


I'm new to LINQ, so I'm guessing my issue is probably pretty basic;

I've created a new datacontext and have executed a query on it.


SomeDataContext dc = new SomeDataContext(connString);

IEnumerable<Reading> readings =dc.ExecuteQuery<Reading>(SQL, thing1, thing2);

int count_readings = readings.Count();

returns the error
"The query result cannot be enumerated more than once"

I could get the number of records via:

count_readings = (from thing1 in dc.Readings select thing1).Count();
but thats not very useful!

Help much appreciated!

Who is Participating?
Richard LeeConnect With a Mentor Software EnthusiastCommented:
Try this:

var readings =dc.ExecuteQuery<Reading>(SQL, thing1, thing2).ToArray();
int count_readings = readings.Length;

Shaun KlineLead Software EngineerCommented:
According to, Count() is not "truly" implemented for IEnumerable, even though it appears as a method of the object. If you need a count, the suggestion is to return your objects into either a ICollection or IList as both of them support Count(). Otherwise, you would need to iterate through your IEnumerable to find the count.
Spike_66Author Commented:
Excellent and simply explained
Richard LeeSoftware EnthusiastCommented:
Glad to help!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.