C# DataTable Count Number Of Rows In A Range

10,079

The logical && in the datatable filter syntax is simply "AND", so change it to:

Int32 range25To49 = 
Convert.ToInt32(answersDataTable.Compute("COUNT(Response)", 
                                         "Response > 75 AND Response < 50"));

The error you're receiving is self-explanatory: your trying to apply a logical && between two string filters, i.e. "Response > '75'" and "Response < '50'", and of course it is not possible.

You must create a filter that contains both the conditions instead, as shown in my previous code snippet.

Also, the single quotes around the numbers are not necessary (even if it seems to work as well).

EDIT :

If the type of Response column is not numeric but a string, you can use Convert() function e.g. :

Int32 range25To49 = 
Convert.ToInt32(
answersDataTable.Compute("COUNT(Response)", 
"Convert(Response,'System.Int32') > 75 AND Convert(Response,'System.Int32') < 50"));
Share:
10,079
HGomez
Author by

HGomez

Hello Sir.

Updated on June 04, 2022

Comments

  • HGomez
    HGomez almost 2 years

    I am trying to compute and count the number of rows inside a C# DataTable that are between a certain range.

    I would like the number(count) of rows where the value in the Responses column is between 25 and 49. However I am not sure how to complete the following line of code.

    I am receiving the error "Operand && cannot be applied to type 'string' and 'string'. I have tried converting the statement to Int32 but it still will not compile. How can I correctly type this statement?

    // Populate datatable from the database.    
    answersDataTable = GetData.getIndividualQuestionResponsesOpenEndedAndRange(questionId);
    
    Int32 range25To49 = Convert.ToInt32(answersDataTable.Compute("COUNT(Response)", "Response > '75'" && "Response < '50'"));
    
  • HGomez
    HGomez about 12 years
    The code compiles, but appears not to be counting any values. There should be 3. But it returns 0. The column datatype in the SQL Server database is NVarChar. Is this the problem?
  • digEmAll
    digEmAll about 12 years
    @Rupert: Yes it could be... try to wrap the numbers inside a convert e.g. Convert(Response, 'System.Int32') > 75