Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Shortcut for c# null and Any() checks [duplicate]

Tags:

Often in C# I have to do this

if(x.Items!=null && x.Items.Any())
{ .... }

Is there a short cut on a collection ?

like image 499
Ian Vink Avatar asked Mar 06 '15 17:03

Ian Vink


People also ask

What is shortcut key A to Z?

Ctrl + A → Select all content. Ctrl + Z → Undo an action. Ctrl + Y → Redo an action. Ctrl + D → Delete the selected item and move it to the Recycle Bin.

What does Ctrl Z do in C?

Ctrl+z − It is used to stop the execution of the program, all the tasks related to the process are shut and execution is suspended.


2 Answers

In C# 6, you'll be able to write:

if (x.Items?.Any() == true)

Before that, you could always write your own extensions method:

public static bool NotNullOrEmpty<T>(this IEnumerable<T> source)
{
    return source != null && source.Any();
}

Then just use:

if (x.NotNullOrEmpty())

Change the name to suit your tastes, e.g. NullSafeAny might be more to your liking - but I'd definitely make it clear in the name that it's a valid call even if x is null.

like image 95
Jon Skeet Avatar answered Oct 13 '22 04:10

Jon Skeet


I also do a check on items of the list to assure the list not just contains all null objects; so as enhancement to Jon Skeet answer:

public static bool NotNullOrEmpty<T>(this IEnumerable<T> source)
{
    return source != null && !source.All(x => x == null);
}
like image 45
alsafoo Avatar answered Oct 13 '22 04:10

alsafoo