Reputation: 417
I have some .NET 4.5 code:
var result = db.storedProcedure(param)
if (!result.Any()) { return; }
foreach (var entry in result)
{
// Some code...
}
At the foreach
, an exception is throw:
The query results cannot be enumerated more than once.
How can I check if result
is empty? I've also tried if (result.Count() == 0)
and that also throws the same exception at the foreach
loop. I've also tried foreach (var entry in result.ToList())
and that also throws the same exception.
I have tried following the suggestions here and here, with no luck.
I've also tried:
var result = db.storedProcedure(param)
if (!result.Any()) { return; }
var resultList = result.ToList();
foreach (var entry in resultList) {}
And I still get the same exception at that foreach
loop as well.
There must be some way to easily check if a Linq result set is empty. What am I doing wrong?
Upvotes: 2
Views: 916
Reputation: 16137
Why do you even to make that check at all? Your loop won't even run at all if there's nothing in result
. Just have this:
var result = db.storedProcedure(param)
foreach (var entry in result)
{
// Some code...
}
return;
Upvotes: 2
Reputation: 101681
Just put the result into a List before iterating:
var result = db.storedProcedure(param).ToList();
if (result.Count == 0) { return; }
Upvotes: 7