Reputation: 21406
I have a DataTable with a column called 'UID' of type string.
What would be best way to verify that each value is an integer in this column?
One approach is to loop through each row as in code below (dt variable is a populated DataTable object) and then check the value for UID column using integer.Parse in a try catch block, but may be there is an easier LINQ-based approach.
if( dt!=null)
{
try
{
foreach (DataRow row in dt.Rows)
{
int.Parse(row["UID"].ToString());
}
}
catch (Exception ex)
{
throw;
}
}
Upvotes: 0
Views: 1833
Reputation: 41
Try this
var table = YourTable;
int invalidDataCount = table.AsEnumerable().Where(d => d.Field<string>("UID").Contains('-')).Count();
if (invalidDataCount > 0) {
throw new Exception();
}
Upvotes: 0
Reputation: 460108
You should use int.TryParse
instead, you can use Enumerable.All
to shorten the code:
int i;
bool allInts = table.AsEnumerable()
.All(r => int.TryParse(r.Field<string>("UID"), out i));
Upvotes: 1