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
Take a look at this opensource library: Nzr.ToolBox
public static bool IsEmpty(this System.Collections.IEnumerable enumerable)
Starting with C#6 you can use null propagation: myList?.Any() == true
If you still find this too cloggy or prefer a good ol' extension method, I would recommend Matt Greer and Marc Gravell's answers, yet with a bit of extended functionality for completeness.
Their answers provide the same basic functionality, but each from another perspective. Matt's answer uses the string.IsNullOrEmpty-mentality, whereas Marc's answer takes Linq's .Any()
road to get the job done.
I am personally inclined to use the .Any() road, but would like to add the condition checking functionality from the method's other overload:
public static bool AnyNotNull<T>(this IEnumerable<T> source, Func<T, bool> predicate = null)
{
if (source == null) return false;
return predicate == null
? source.Any()
: source.Any(predicate);
}
So you can still do things like :
myList.AnyNotNull(item=>item.AnswerToLife == 42);
as you could with the regular .Any()
but with the added null check
Note that with the C#6 way: myList?.Any()
returns a bool?
rather than a bool
, which is the actual effect of propagating null
Here's a modified version of @Matt Greer's useful answer that includes a static wrapper class so you can just copy-paste this into a new source file, doesn't depend on Linq, and adds a generic IEnumerable<T>
overload, to avoid the boxing of value types that would occur with the non-generic version. [EDIT: Note that use of IEnumerable<T>
does not prevent boxing of the enumerator, duck-typing can't prevent that, but at least the elements in a value-typed collection will not each be boxed.]
using System.Collections;
using System.Collections.Generic;
public static class IsNullOrEmptyExtension
{
public static bool IsNullOrEmpty(this IEnumerable source)
{
if (source != null)
{
foreach (object obj in source)
{
return false;
}
}
return true;
}
public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
{
if (source != null)
{
foreach (T obj in source)
{
return false;
}
}
return true;
}
}
This may help
public static bool IsAny<T>(this IEnumerable<T> enumerable)
{
return enumerable?.Any() == true;
}
public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
return enumerable?.Any() != true;
}
Sure you could write that:
public static class Utils {
public static bool IsAny<T>(this IEnumerable<T> data) {
return data != null && data.Any();
}
}
however, be cautious that not all sequences are repeatable; generally I prefer to only walk them once, just in case.
I use this one:
public static bool IsNotEmpty(this ICollection elements)
{
return elements != null && elements.Count > 0;
}
Ejem:
List<string> Things = null;
if (Things.IsNotEmpty())
{
//replaces -> if (Things != null && Things.Count > 0)
}