Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

c#-6.0

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?

like image 651
JohnC Avatar asked Oct 26 '15 09:10

JohnC


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.


2 Answers

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 w.b mentioned in the comments, if you're looking for another item than the first one you can use ElementAtOrDefault instead of FirstOrDefault

like image 138
i3arnon Avatar answered Oct 15 '22 16:10

i3arnon


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();
like image 24
w.b Avatar answered Oct 15 '22 16:10

w.b