Yoda
Yoda

Reputation: 18068

Any shorthand for comparision to null or required value?

Is there any clever shorthand in C# to this:

list.Where(x=> x.a.b == null || x.a.b == desiredIntValue)

Upvotes: 0

Views: 43

Answers (1)

Guru Stron
Guru Stron

Reputation: 143373

In later C# versions you can use pattern matching with logical patterns, specifically or in this case (assuming list is IEnumerable<> since the newer language features usually are not supported by expression trees) and constants:

const int desiredIntValue = 1;
list.Where(x=> x.a.b is null or desiredIntValue)

For non-constant values you can do something like:

list.Where(x => (x.a.b ?? desiredIntValue) == desiredIntValue);

Or for nullable value types

list.Where(x => x.a.b.GetValueOrDefault(desiredValue) == desiredValue);

But not sure if it can be considered as shorthand.

Upvotes: 4

Related Questions