I am checking two conditions which is following in C#:
if (result.Data.Count > 0)
{
if(result.Data[0].AdditionalData != null)
{
// To Do
}
}
My confusion is there is any better way to check these in a single if condition?
I am trying to use Null-Condition operator, but did not work it. Null-Conditional operator in MSDN
5
Answers
You can create extension method on IEnumerable and use it
Like written also by @Hans Killian try to use the extensions already there for
IEnumerables
In your case I think
.ElementAtOrDefault(0)
(or if you always want to use index 0 just use.FirstOrDefault()
) is the best fit for you here.Full working example can be found here
Null conditional can work along with
Any
, and short-circuiting the next checkExplanation of each of the steps
result?
Is result not null?
Data?
if so, is Data not null?
Any()
if so, does Data have any items?
Data[0]?
if so, is the first item not null? (the reason I use index here is because you may want to check the nth item, so
FirstOrDefault
may be too restrictive)AdditionalData != null
if so, is Additional data not null?
Of course, if any of these checks are unnecessary or superfluous you can remove the specific check from the chain (remove
?
in the case of null-conditional). Here the checks are all laid out clearly in one line so it’s simple to modify the chain of logic.One liner using
System.Linq
.I think the best way to have clean and good code is to use FluentValidation. Please note the following code snippet:
The above code is an example of validating a model to check null, empty and etc. and this code must check validation in business logic:
It is very simple to use and very clean. You can even perform multiple checks and get results through the error list
This link is the site address of FluentValidation