C# 6 null conditional operator check for .Any()?
In the example shown here (and on numerous other websites) with regards to the null-conditional operator, it states that
int? first = customers?[0].Orders.Count();
can be used to get the count for the first customer. But this statement does not check for the existence of customers in the collection and can throw an index out of range exception. What should be the correct (preferably single-lined) statement that takes care of checking for the existence of elements?
The null conditional operator is intended for conditionally accessing null
but this isn't the issue you're having.
You are trying to access an empty array . You can turn that into a case of accessing null with FirstOrDefault
and use the operator on that:
int? first = customers.FirstOrDefault()?.Orders.Count();
If the array isn't empty it will operate on the first item, and if it is empty FirstOrDefault
will return null
which will be handled by the null conditional operator.
Edit: As wb mentioned in the comments, if you're looking for another item than the first one you can use ElementAtOrDefault
instead of FirstOrDefault
You can use LINQ's DefaultIfEmpty
, it will yield a singleton IEnumerable
in case the collection queried is empty:
int? first = customers?.DefaultIfEmpty().First().Orders.Count();
or if you want to use indexing:
int? first = customers?.DefaultIfEmpty().ToArray()[0].Orders.Count();
If I understand the question correctly, you are asking if there's a built-in (or concise) way to protect against IndexOutOfRangeException
s. The closest you'll get to it would be something like:
myArray?.Length > 42 ? myArray[42] : null
or as @wb mentioned, utilize ElementAtOrDefault:
myArray?.ElementAtOrDefault(42)
both of those will protect against NullReferenceException
as well as IndexOutOfRangeException
.
上一篇: 不区分大小写的字符串比较C ++
下一篇: .Any()的C#6空条件运算符检查?