Solved

Counting records using LINQ

Posted on 2010-11-12
4
696 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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
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…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

832 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