Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for null before I use in linq?

Tags:

c#

linq

I have an list of objects that contains another object in it.

List<MyClass> myClass = new List<MyClass>();

I want to do some linq like this

myClass.Where(x => x.MyOtherObject.Name = "Name").ToList();

Thing is sometimes "MyOtherObject" is null. How do I check for this?

like image 730
chobo2 Avatar asked Apr 08 '11 22:04

chobo2


People also ask

Is NULL in LINQ?

LINQ to SQL does not impose C# null or Visual Basic nothing comparison semantics on SQL. Comparison operators are syntactically translated to their SQL equivalents. The semantics reflect SQL semantics as defined by server or connection settings.

How do you handle NULL values in LINQ query?

An object collection such as an IEnumerable<T> can contain elements whose value is null. If a source collection is null or contains an element whose value is null , and your query doesn't handle null values, a NullReferenceException will be thrown when you execute the query. var query1 = from c in categories where c !=

Does LINQ query return NULL?

in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;) Oh, your explanation helps further understanding. Thank you !

IS NULL check in C#?

In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.


2 Answers

Simple, just add an AND clause to check if it's not null:

myClass.Where(x => x.MyOtherObject != null && x.MyOtherObject.Name = "Name").ToList();
like image 184
alexn Avatar answered Oct 16 '22 11:10

alexn


As of C# 6, you can also use a null conditional operator ?.:

myClass.Where(x => x.MyOtherObject?.Name == "Name").ToList();

This will essentially resolve the Name property to null if MyOtherObject is null, which will fail the comparison with "Name".

Try it online

like image 9
DiplomacyNotWar Avatar answered Oct 16 '22 13:10

DiplomacyNotWar