Often in C# I have to do this
if(x.Items!=null && x.Items.Any())
{ .... }
Is there a short cut on a collection ?
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With