Stop LINQ Query if Default Value is Returned at Any Point
Is there syntactic sugar or a method to "short-circuit" a LINQ statement
within the same line when written in fluent syntax? For example if null is
returned by a FirstOrDefault call, is it possible to return null otherwise
continue with the rest of the method chain?
List<string> testList = new List<string>() { "some", "strings" };
var reversed = testList.FirstOrDefault(x => x == "hello").Reverse();
The FirstOrDefault call will return null so the statement will throw an
ArgumentNullException on the Reverse call. Is there a way of stopping
before the Reverse call since the default value was returned at that
point?
(I know that the query can be broken into another line and default(T) can
be checked before Reverse or, for simple cases, the conditional operator
(?:) can be used but I'm curious if I'm missing a particular feature for
longer/more complex chains)
Edit - To clarify this is just an example to show the idea, it's not part
of any actual code. I'd like to avoid exceptions being thrown as it would
be more performant to just split the line and do a check.
No comments:
Post a Comment