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

Gani_tpt 1,506 Reputation points
2021-04-12T15:19:50.527+00:00

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.

C#
C#
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.
10,247 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,036 Reputation points
    2021-04-12T15:30:12.69+00:00

    Try this or a variation

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

0 additional answers

Sort by: Most helpful