C # 6 null conditional statement operator for .Any ()?

In the example given here ( and on other other sites ) in relation to the operator with a null condition, he claims that

int? first = customers?[0].Orders.Count(); 

can be used to get an invoice for the first customer. But this statement does not check for clients in the collection and may cause exclusion from a range out of range. What should be the correct (preferably one-line) operator that takes care of checking for the existence of elements?

+4
source share
3 answers

The null condition statement is for conditional accessnull , but this is not the problem you are facing.

. null FirstOrDefault :

int? first = customers.FirstOrDefault()?.Orders.Count(); 

, , , FirstOrDefault null, .

: w.b, , , ElementAtOrDefault FirstOrDefault

+5

LINQ DefaultIfEmpty, IEnumerable , :

int? first = customers?.DefaultIfEmpty().First().Orders.Count();

:

int? first = customers?.DefaultIfEmpty().ToArray()[0].Orders.Count();
+2

, , ( ) IndexOutOfRangeException s. :

myArray?.Length > 42 ? myArray[42] : null

@w.b. , ElementAtOrDefault:

myArray?.ElementAtOrDefault(42) 

NullReferenceException, IndexOutOfRangeException.

0

Source: https://habr.com/ru/post/1613168/


All Articles