Search code examples
c#linqdatareader

c# LINQ find value in datareader


This is my table on MySQL database :

+----------+--------+---------+
| UserName | Region | UsercIX |
+----------+--------+---------+
| a123456  | X410   | NULL    |
| a123456  | X420   |       1 |
| a123456  | X430   | NULL    |
| a123456  | X440   |       1 |
+----------+--------+---------+

The user a123456 is write enabled for X420 and X440 Region (UsercIX=1) and reading for X410 and X430 Region (UsercIX=NULL).

I need to find in this table -via LINQ or your suggestion- only values equals to 1 in the column UsercIX, because with DataReader extracting the first value of the column which is null.

Please an you help me ?

My code below

using (OdbcDataReader reader = command.ExecuteReader())
{
    if (reader.HasRows)
    {
        while (reader.Read())
        {
           int UsercIX = Convert.ToInt32(reader["UsercIX"]);  //IS NULL
        }
    }
}

Edit #01

using (OdbcDataReader reader = command.ExecuteReader())
{
    if (reader.HasRows)
    {
        while (reader.Read())
        {
            int UsercIX = reader.GetInt32(6);
        }
    }                            
}

Solution

  • May i suggest doing a try parse on the value?

         int number;
    
         bool success = Int32.TryParse((reader["UsercIX"], out number);
         if (success)
         {
                 // it worked, yay
         }
         else
         {
                 // 😥
         }