How to check if IEnumerable is null or empty?
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.
Cannot find Any method of IEnumerable to do empty check
There is no need for an explicit Any
check or null
check.
foreach (var x in (dataValue ?? Enumerable.Empty<Data>()))
is what I would suggest, since it avoids the double enumeration problem of using Any
(and it treats null
as equivalent to empty). So this might look like:
private bool Process()
{
bool returnValue = false;
IEnumerable<Data> dataValue = GetData();
foreach (var x in (dataValue ?? Enumerable.Empty<Data>()))
{
returnValue = true;
// iterating over dataValue here and extracting each field of Data class
}
return returnValue;
}
Checking if a generic IEnumerable is empty
Since the type may be unknown, you can try check for IEnumerable
interface and use MoveNext()
on the enumerator.
EDIT: I updated the method name. It makes more sense with the logic now since the original question code was checking if there were items in the collection.
public bool IsNotNullOrEmpty(object enumerable)
{
if (enumerable != null)
{
if (enumerable is IEnumerable)
{
using(var enumerator = ((IEnumerable)enumerable).GetEnumerator())
return enumerator.MoveNext();
}
}
return false;
}
IEnumerable is empty?
You want IEnumerable.Any() extension method (.Net Framework 3.5 and above). It avoids counting over the elements.
Does C# have IsNullOrEmpty for List/IEnumerable?
nothing baked into the framework, but it's a pretty straight forward extension method.
See here
/// <summary>
/// Determines whether the collection is null or contains no elements.
/// </summary>
/// <typeparam name="T">The IEnumerable type.</typeparam>
/// <param name="enumerable">The enumerable, which may be null or empty.</param>
/// <returns>
/// <c>true</c> if the IEnumerable is null or empty; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null)
{
return true;
}
/* If this is a list, use the Count property for efficiency.
* The Count property is O(1) while IEnumerable.Count() is O(N). */
var collection = enumerable as ICollection<T>;
if (collection != null)
{
return collection.Count < 1;
}
return !enumerable.Any();
}
Daniel Vaughan takes the extra step of casting to ICollection (where possible) for performance reasons. Something I would not have thought to do.
c# check IEnumerable for null
One of the subsequent x.Person.SystemUsers
could be null. .Any()
returns true if there is one. If you then try to ToList()
afterwards, you might find an x
who's Person
is null.
Check to make sure that x.Person
isn't null before accessing a property on the object.
Is null checking required for IEnumerable object?
You do not need to check if selectedRows
is null
. The returned IEnumerable<>
might be empty, but it will never be null
.
As an aside, I'd suggest you simplify your code by writing:
var selectedRows
= ugTable.Rows.Cast<Infragistics.Win.UltraWinGrid.UltraGridRow>()
.Where(drow => drow != null && drow.Selected);
Which is shorter and equivalent.
To check if IEnumerable is not null before checking for Any() in c#
The ?.
or null conditional operator syntax skips evaluation of the rest of the expression and evaluates null if the left side value is null. So myIEnumerableCollection?.Any()
will give a type of bool?
i.e. either null, true, or false. The ?? false
, or null coalescing operator, convert the null-case to false.
Related Topics
Is It Necessary to Manually Close and Dispose of SQLdatareader
When Using Trusted_Connection=True and SQL Server Authentication, Will This Affect Performance
How to Invoke a UI Method from Another Thread
Will the Dynamic Keyword in C#4 Support Extension Methods
Mysqlcommand Command.Parameters.Add Is Obsolete
How to View Msil/Cil Generated by C# Compiler? Why Is It Called Assembly
Cannot Set Some Http Headers When Using System.Net.Webrequest
Single App.Config Multi-Project C#
How to Sum Up an Array of Integers in C#
Deleting Specific Rows from Datatable
Background Color of a Listbox Item (Windows Forms)
Move Window When External Application's Window Moves
Why Is Ushort + Ushort Equal to Int
Outofmemoryexception While Populating Memorystream: 256Mb Allocation on 16Gb System