Solved

Counting records using LINQ

Posted on 2010-11-12
4
697 Views
Last Modified: 2013-11-11
HI

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.

i.e;

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!


0
Comment
Question by:Spike_66
  • 2
4 Comments
 
LVL 26

Expert Comment

by:Shaun Kline
ID: 34121158
According to http://stackoverflow.com/questions/168901/howto-count-the-items-from-a-ienumerablet-without-iterating, 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.
0
 
LVL 18

Accepted Solution

by:
Richard Lee earned 125 total points
ID: 34121273
Try this:

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

DaTribe
0
 

Author Closing Comment

by:Spike_66
ID: 34121411
Excellent and simply explained
0
 
LVL 18

Expert Comment

by:Richard Lee
ID: 34121855
Glad to help!
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question