ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

IsNullOrEmpty

Determines whether a collection is null or has no elements without having to enumerate the entire collection to get a count.

Source

/// <summary>
/// Determines whether a collection is null or has no elements without having to enumerate the entire collection to get a count.  Uses LINQ.
/// </summary>
/// <typeparam name="T">The item type.</typeparam>
/// <param name="items">The items.</param>
/// <returns>
/// <c>true</c> if this list is null or empty; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmpty<T>(this IList<T> items)
{
    return items == null || !items.Any();
}

Example

var list = new List<string>();
list.Add("Test1");
list.Add("Test2");
Assert.IsFalse(list.IsNullOrEmpty());
list.Clear();
Assert.IsTrue(list.IsNullOrEmpty());
list = null;
Assert.IsTrue(list.IsNullOrEmpty());

Author: Kelly Adams

Submitted on: 15 okt. 2010

Language: C#

Type: System.Collections.Generic.IList<T>

Views: 10765