boski
boski

Reputation: 1146

Linq - check condition in where clause if field can be null

I have question - how to check condition in where clause even when item has no reference?

Most basic way - I am checking field from my Class, which can be null. When I just check it in that way it will return Null Reference Exception

 var soldOutProducts = from p in list 
            where p.destinataire.StartsWith("D") 
            select p; 

Upvotes: 2

Views: 33444

Answers (3)

user2046117
user2046117

Reputation:

can you do

var soldOutProducts = from p in list
                      where !string.IsNullOrEmpty(p.destinataire) and
                            p.destinataire.StartsWith("D")
                      select p;

Upvotes: 5

semao
semao

Reputation: 1757

 var soldOutProducts = from p in list 
            where p.destinataire != null && p.destinataire.StartsWith("D") 
            select p; 

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1504172

Just check for null first, just as you would if you were writing normal C# code in a loop.

where p.destinataire != null && p.destinataire.StartsWith("D")

If p itself can be null (i.e. your list can contain null elements) then you need to check for that too:

where p != null && p.destinataire != null && p.destinataire.StartsWith("D")

Note that if your query expression is just doing filtering, you might want to use dot notation instead:

var soldOutProducts = list.Where(p => p.destinataire != null && 
                                      p.destinataire.StartsWith("D"));

Query expressions are really beneficial when the query gets complicated - particularly with joins and grouping.

Upvotes: 7

Related Questions