Pranay Rana
Pranay Rana

Reputation: 176896

Check datatable column contains numeric values

I want to find only those row form table which contains numeric values , so for that I did as following

dtDetails.Select(" (ISNUMERIC(OriginatingTransit)=0)")

but it throws exception

The expression contains undefined function call ISNUMERIC().

Upvotes: 0

Views: 6251

Answers (1)

Andras Zoltan
Andras Zoltan

Reputation: 42343

You'll have to do that at the database level, or loop through yourself and write something that checks if a value can be parsed into a number. The Select method does not support what you're trying to do: Expression property on MSDN, contains info about what's supported.

bool IsNumeric(object o)
{
  decimal result_ignored;
  return o != null && 
    !(o is DBNull) && 
    decimal.TryParse(Convert.ToString(o), out result_ignored);
}

And then you can do something like this:

var filtered = dtDetails.Rows.Cast<DataRow>().
  Where(r => IsNumeric(r["OriginatingTransit"]));

If you then enumerate filtered, you will get only those with numeric values in that column.

This isn't perfect - because as some comments mention on the answer linked to by Surjit Samra in the comments to your question above, the exact meaning of 'is numeric' is loose. This goes for the widest possible description, I think, by using decimal to attempt to parse the value. You could use a different type (e.g. int or float), or a regular expression, perhaps, if your requirements are tighter.

Upvotes: 1

Related Questions