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
Without custom helpers I recommend either ?.Any() ?? false
or ?.Any() == true
which are relatively concise and only need to specify the sequence once.
When I want to treat a missing collection like an empty one, I use the following extension method:
public static IEnumerable<T> OrEmpty<T>(this IEnumerable<T> sequence)
{
return sequence ?? Enumerable.Empty<T>();
}
This function can be combined with all LINQ methods and foreach
, not just .Any()
, which is why I prefer it over the more specialized helper functions people are proposing here.
The way I do it, taking advantage of some modern C# features:
Option 1)
public static class Utils {
public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
return !(list?.Any() ?? false);
}
}
Option 2)
public static class Utils {
public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
return !(list?.Any()).GetValueOrDefault();
}
}
And by the way, never use Count == 0
or Count() == 0
just to check if a collection is empty. Always use Linq's .Any()
I used simple if to check for it
check out my solution
foreach (Pet pet in v.Pets)
{
if (pet == null)
{
Console.WriteLine(" No pet");// enumerator is empty
break;
}
Console.WriteLine(" {0}", pet.Name);
}
I had the same problem and I solve it like :
public bool HasMember(IEnumerable<TEntity> Dataset)
{
return Dataset != null && Dataset.Any(c=>c!=null);
}
"c=>c!=null" will ignore all the null entities.