HGomez
HGomez

Reputation: 1534

C# DataTable Count Number Of Rows In A Range

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'"));

Upvotes: 2

Views: 11078

Answers (2)

digEmAll
digEmAll

Reputation: 57210

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"));

Upvotes: 3

ionden
ionden

Reputation: 12776

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

Upvotes: 0

Related Questions