Alex Rivera | Logout

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

Asked 2011-03-09T15:46:25.563
66

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
Edit
Report

1 Answer

91

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"?

answered 2011-03-09T15:52:48.547

Your Answer