How to handle null values in LINQ select statement in C#

Gani_tpt 1,221 Reputation points

I am getting Object reference error. because of null values.

How to handle null values in LINQ Select statement

string Qtyvalues = dtQty.AsEnumerable().Select(p => p.Field<string>("KEYMATERIALS").ToString()).FirstOrDefault();

Error : object reference.

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
7,010 questions
No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 29,236 Reputation points Microsoft MVP

    Try this or a variation

    var Qtyvalues = dtQty
        .Where(x => x["COL3"] != DBNull.Value)
        .Select(p => p.Field<string>("QTY"));

0 additional answers

Sort by: Most helpful