0

I am trying to get a single row from a data table using LINQ. It seems to getting the record but I am not able to work with it. Not sure what I am doing wrong. My LINQ query is below:

IEnumerable<DataRow> query = 
      from myRow in dataTable.AsEnumerable()
      where myRow.Field<int>("AM2MIN") <= Convert.ToInt32(minimumValue) &&
            myRow.Field<int>("AM2MAX") >= Convert.ToInt32(minimumValue)
      select myRow;

When I do the following to see if any records exist, it errors out.

if (query.Any())
{

}

InvalidCastException seems to be the consistent error.

Any help is much appreciated!

4
  • 1
    What does it say you're trying to cast it to? Nov 16, 2012 at 21:21
  • 1
    Another thought, is it possible that the AM2MIN field is not actually an int? Nov 16, 2012 at 21:23
  • What database type is AM2MIN and AM2MAX. The invalid cast could be because they are not INT but rather SMALLINT, BIGINT, etc.
    – McGarnagle
    Nov 16, 2012 at 21:23
  • It just says 'Specified cast is not valid.'
    – Chris
    Nov 16, 2012 at 21:24

1 Answer 1

0

Looks like one of your fields does not contain integer value.

Verify Data Type of those columns. Also verify if Nulls are allowed for them. If data type is int, but nulls are allowed, then cast to nullable int: myRow.Field<int?>("AM2MIN") and verify if it has value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.