简体   繁体   中英

Object reference not set to an instance of an object in LINQ C#

I have a DataTable called dtMondayNewsLetter and when the DT returns no rows. ie Empty

it shows an error Object reference not set to an instance of an object

CODE

CurrentDirection = Convert.ToString((from DataRow dr in dtMondayNewsLetter.Rows 
                    where (int)dr["PostID"] == PostID select (string)dr["Direction"])
                           .FirstOrDefault()).Trim();

What changes I need to do in above code to eliminate the error.

As you mentioned, query

from DataRow dr in dtMondayNewsLetter.Rows 
where (int)dr["PostID"] == PostID 
select (string)dr["Direction"]

returns no rows, so FirstOrDefault() returns null .

so you can do a simply if to check wheter result is available..

var resultString = (from DataRow dr in dtMondayNewsLetter.Rows
                    where (int)dr["PostID"] == PostID 
                    select (string)dr["Direction"])
                   .FirstOrDefault();

if (resultString != null) 
{
    CurrentDirection = resultString.Trim();
}
else
{
    //case, when no rows
}

To expand on my comment, I would do something like:

foreach (DataRow dr in dtMondayNewsLetter.Rows)
{
    if (dr["PostID"] != DBNull.Value && dr["Direction"] != DBNull.Value)
    {
        if ((int)dr["PostID"] == PostID)
        {
            CurrentDirection = dr["Direction"].ToString();
        }
    }
}

Trying to be concise by shoving everything into a LINQ statement is not always optimal. In your case, there could be a number of objects, or data, which is NULL , thus causing the null reference exception exception.

Inside a one line LINQ statement, it's very difficult to figure out where the NULL object is. Splitting that LINQ statement into a for...each loop makes things a lot easier, and achieves the exact same result.

However, if "PostID" and "Direction" are non-nullable (thus no need to use DBNull.Value checks), then use @nopeflow answer, as that is much safer then your current implementation.

You can use Null-Coalescing Operator . in case that FirstOrDefault returns null return empty string.

CurrentDirection =
    Convert.ToString(
        (from DataRow dr in dtMondayNewsLetter.Rows
            where (int) dr["PostID"] == PostID
            select (string) dr["Direction"]).FirstOrDefault() ?? "").Trim();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM