Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 703
  • Last Modified:

Counting records using LINQ

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
Spike_66
Asked:
Spike_66
  • 2
1 Solution
 
Shaun KlineLead Software EngineerCommented:
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
 
Richard LeeSoftware EnthusiastCommented:
Try this:

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

DaTribe
0
 
Spike_66Author Commented:
Excellent and simply explained
0
 
Richard LeeSoftware EnthusiastCommented:
Glad to help!
0

Featured Post

Restore individual SQL databases with ease

Veeam Explorer for Microsoft SQL Server delivers an easy-to-use, wizard-driven interface for restoring your databases from a backup. No expert SQL background required. Web interface provides a complete view of all available SQL databases to simplify the recovery of lost database

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now