Search code examples
c#datatablenullreferenceexceptionasenumerable

C# Nullreferenceexception in DataTable.AsEnumerable() Where


The Where clause has at least 1 Datarow as a result as I know for sure.

And I checked != null before calling 1) Select 2) DefaultIfEmpty method of course and it passed without a problem.

I also tried to use ?? false but don't know the exact mechanism it works and how to use it.

The columns are all Nullable.

I don't know what is wrong here...looking for solution all day.. Because I'm self-learning programmer, I'm really lack of fundamental knowledge.

dt.AsEnumerable().Where(dr => (dr.Field<string>("name_first_API").Contains("Ibuprofen")
                            || dr.Field<string>("name_first_API").Contains("Dexibuprofen")
                            || dr.Field<string>("name_first_API").Contains("Naproxen")
                            || dr.Field<string>("name_first_API").Contains("Meloxicam"))
                            && dr.Field<DateTime>("rx_visitdate").Date >= DateTime.Today.AddYears(-3)).
                  Select(dr => dr.Field<int>("howlongday_rx")).
                  DefaultIfEmpty(0).Sum();

Solution

  • If all can be null you could use:

    string[] meds = { "Ibuprofen", "Dexibuprofen", "Naproxen", "Meloxicam" };
    int sum = dt.AsEnumerable()
        .Select(dr => new
        {
            name = dr.Field<string>("name_first_API"),
            visit = dr.Field<DateTime?>("rx_visitdate"),
            howlong = dr.Field<int?>("howlongday_rx")
        })
        .Where(x => meds.Contains(x.name, StringComparer.InvariantCultureIgnoreCase)
                    && x.visit?.Date >= DateTime.Today.AddYears(-3))
        .Sum(x => x.howlong ?? 0);