user5019819
user5019819

Reputation: 63

LINQ return 0 if query from DataTable is null

Hi Everyone I have the following query. On occasion, there are no results for this query, and I will need it to return a 0, rather than an error.

var count= dt.AsEnumerable().Where(x => x.Field<string>("names").Equals(name) && x.Field<string>("port").Equals("true")).Count(); 

I have tried adding ?? 0 but the compiler doesn't like that.

thanks for the help!

Upvotes: 0

Views: 1742

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460138

Enumerable.Count doesn't throw an error if the sequence is empty, it returns 0. Do you instead mean that dt can be null? So either the DataTable is null or one of the strings is null. You don't need to use String.Equals you can use == to compare strings meaningfully, then you don't get an exception. You can also use this shorter way using the overload of Count:

if(dt == null) return 0;
return dt.AsEnumerable()
    .Count(x => x.Field<string>("names") == name && x.Field<string>("port") == "true");

Upvotes: 2

Cyril Gandon
Cyril Gandon

Reputation: 17058

Yoda comparison for handle case when you have null in database:

var count= dt.AsEnumerable()
             .Where(x => name.Equals(x.Field<string>("names")) 
                      && "true".Equals(x.Field<string>("port")))
             .Count();

enter image description here

Upvotes: 0

Paweł Reszka
Paweł Reszka

Reputation: 1557

Do this:

var count=dt != null ? dt.AsEnumerable().Where(x => x.Field<string>("names").Equals(name) && x.Field<string>("port").Equals("true")).Count() : 0; 

It will simply check if dt is null before any operations on dt are executed.

Upvotes: 0

Related Questions