Search code examples
c#shorthand

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)

Solution

  • 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.