Search code examples
c#asp.netlinqexceptionobject-reference

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. i.e. 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.


Solution

  • 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();