Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# LINQ see how many rows an ISingleResult returns help!

Tags:

c#

Hi am using ISingleResult with an Stored procedure. How do i check in C# if the Isingler is empty or not. Because sometime the SP returns nothing and sometime is returns data.

Is there anyway to se how many rows the ISingleResult contains. Thanks for help.

like image 351
Tan Avatar asked Dec 14 '22 01:12

Tan


2 Answers

You can convert the result to a list (using the LINQ ToList method) or to an array (with ToArray), and then check the count/length from there.

List<T> result = YourStoredProcedureCall().ToList();

if (result.Count > 0) 
{
    // Deal with results here
}

As mentioned by Cullen's answer, you can get the number of returned results by using the Count() method. Please note that this will internally iterate through the list to calculate the count, which is not optimal if you're just trying to determine if you have 1 or more results.

NOTE:

For any of these, please be sure that you have the following using statement in your source file:

using System.Linq;

EDIT NOTE:

I had originally suggested using the Any() method directly on the ISingleResult result, but this will most likely result in an exception saying 'The query results cannot be enumerated more than once.' if you then try to enumerate the ISingleResult again. Converting into an array or list first avoids this exception. From there, you can still use Any() on the array/list, or you can evaluate the Count or Length property directly as shown in the code example.

like image 56
Josh Sklare Avatar answered Feb 16 '23 15:02

Josh Sklare




    ISingleResult result =
        db.CustomersByCity("London");
    // check the result
    return (result != null && result.count() > 0) 

like image 33
Leo Nix Avatar answered Feb 16 '23 17:02

Leo Nix