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
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 !=
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.
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.
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"?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With