I love string.IsNullOrEmpty
method. I\'d love to have something that would allow the same functionality for IEnumerable. Is there such? Maybe some collection he
public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source)
{
return source != null && source.Any();
}
my own extension method to check Not null and Any
Jon Skeet's anwser (https://stackoverflow.com/a/28904021/8207463) has a good approach using Extension Method - Any() for NULL and EMPTY. BUT he´s validating the questions´owner in case for NOT NULL. So carefully change Jon´s approach to validate AS NULL to:
If (yourList?.Any() != true)
{
..your code...
}
DO NOT use ( will not validate AS NULL):
If (yourList?.Any() == false)
{
..your code...
}
You can also in case validating AS NOT NULL ( NOT tested just as example but without compiler error) do something like using predicate :
If (yourList?.Any(p => p.anyItem == null) == true)
{
..your code...
}
https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,8788153112b7ffd0
For which .NET version you can use it please check:
https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=netframework-4.8#moniker-applies-to
if (collection?.Any() == true){
// if collection contains more than one item
}
if (collection?.Any() != true){
// if collection is null
// if collection does not contain any item
}
Another way would be to get the Enumerator and call the MoveNext() method to see if there are any items:
if (mylist != null && mylist.GetEnumerator().MoveNext())
{
// The list is not null or empty
}
This works for IEnumerable as well as IEnumerable<T>.
The other best solution as below to check empty or not ?
for(var item in listEnumerable)
{
var count=item.Length;
if(count>0)
{
// not empty or null
}
else
{
// empty
}
}
public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable) {
return enumerable == null || !enumerable.Any();
}