Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In LINQ, select all values of property X where X != null

Tags:

c#

linq

Is there a shorter way to write the following? (Something that would check for null without explicitly writing != null)

from item in list  where item.MyProperty != null  select item.MyProperty 
like image 259
Ilya Kogan Avatar asked Mar 09 '11 15:03

Ilya Kogan


People also ask

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 !=

Will LINQ select 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.

IS NOT NULL check in LINQ?

The query needs to look for the values that is not null in any one of the list values (100 or 110 or 120). model = (from line in db. Bibs where line. TNo == "245" && (line.


2 Answers

You can use the OfType operator. It ignores null values in the source sequence. Just use the same type as MyProperty and it won't filter out anything else.

// given: // public T MyProperty { get; } var nonNullItems = list.Select(x => x.MyProperty).OfType<T>(); 

I would advise against this though. If you want to pick non-null values, what can be more explicit than saying you want "the MyProperties from the list that are not null"?

like image 67
R. Martinho Fernandes Avatar answered Sep 22 '22 04:09

R. Martinho Fernandes


You could define your own extension method, but I wouldn't recommend that.

public static IEnumerable<TResult> SelectNonNull<T, TResult>(this IEnumerable<T> sequence,Func<T, TResult> projection) {    return sequence.Select(projection).Where(e => e != null); } 

I don't like this one because it mixes two concerns. Projecting with Select and filtering your null values are separate operations and should not be combined into one method.


I'd rather define an extension method that only checks if the item isn't null:

public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> sequence) {    return sequence.Where(e => e != null); }  public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> sequence)     where T : struct {    return sequence.Where(e => e != null).Select(e => e.Value); } 

This has only a single purpose, checking for null. For nullable value types it converts to the non nullable equivalent, since it's useless to preserve the nullable wrapper for values which cannot be null.

With this method, your code becomes:

list.Select(item => item.MyProperty).WhereNotNull() 
like image 36
CodesInChaos Avatar answered Sep 21 '22 04:09

CodesInChaos