I am counting certain int values (1, 2, 3, or 4) in particular columns of a datatable
. The only values the column can contain are ints between 1 and 9 (exclusive) or null.
For example, a typical column with 10 entries would look like:
Level
1
2
1
4
3
7
3
3
(null)
9
This works fine, despite the null value. As long as there is a non-null, my code works.
The code fails when the column only contains null values, however, which can happen, as I am pulling this data from a database, and depending on the conditions, all the results may be null.
I am using the code shown below to do this count. I looked at this question: Input string was not in a correct format yet I am not sure of a way to use TryParse()
in this context.
int countnum = tab2table.AsEnumerable().Where(x => int.Parse(x["Level"].ToString()) == 1 || int.Parse(x["Level"].ToString()) == 2 ||
int.Parse(x["Level"].ToString()) == 3 || int.Parse(x["Level"].ToString()) == 4).ToList().Count;
For the example Level
column shown above, countnum
should be 7. When the column is all null countnum
should be 0.
How can this be changed to work even when the column is all null? I suppose if there were a way to check if the column if null, I could put this in an if statement, but I have not found a way to do that.