Amiga500
Amiga500

Reputation: 6131

Resolving a null type with LINQ to SQL

Apology first, I am really beginner with the LINQ, hence the question.

I am being unable to catch values that are null form the database. I am making a LINQ to DataTable. I am checking the double type.

This is the code I have:

var results2 = from myRow in table.AsEnumerable()
                                       where myRow.Field<double>("Cost") == 0
                                       select myRow;

That Code works fine if a value is zero. How Do I make it check for null as well?

Another question is also related to this issue:

I have this code:

var results = from myRow in table.AsEnumerable()
                                       where myRow.Field<string>("Name") == "test"
                                       select myRow;

And that works just fine if the value is test. How do I check if the "Name" column is empty/null??

Upvotes: 0

Views: 105

Answers (1)

David L
David L

Reputation: 33833

Add an OR condition with the || operator.

For your nullable double case, you will need to check if it has a value AND is the value you expect, in addition to checking for null.

var results2 = from myRow in table.AsEnumerable()
               where (
                   myRow.Field<double?>("Cost").HasValue &&
                   myRow.Field<double?>("Cost").Value == 0)
               || !myRow.Field<double?>("Cost").HasValue
               select myRow;


var results = from myRow in table.AsEnumerable()
              where myRow.Field<string>("Name") == "test" ||
                    myRow.Field<string>("Name") == null
              select myRow;

Upvotes: 2

Related Questions