Articles » General Programming » Collections » General

IsNullOrEmpty for Generic Collections in C#

Gaurav Kumar Arora, 12 Aug 2015 CPOL 2.3K 8

2.90 (9 votes)

1

2

3

4

5

2.90/5 - 9 votes

μ 2.90, σa 3.10 [?]

In this code snippet, we will see creation and implementation of IsNullOrEmpty for collections.

Can I implement IsNullOrEmpty for my Generic collections/lists?

It's out of C#. Unfortunately, there is only one method which is of a String method String.IsNullOrEmpty() available, framework does not provide us such things.

What is the solution for this?

A solution is only Extension Method, we just need to create an Extension Method which will provide the same facility: Here is the extension method:

public static class CollectioncExtensionMethods
{
public static bool IsNullOrEmpty<T>(this IEnumerable<T> genericEnumerable)
{
return ((genericEnumerable == null) || (!genericEnumerable.Any()));
}

public static bool IsNullOrEmpty<T>(this ICollection<T> genericCollection)
{
if (genericCollection == null)
{
return true;
}
return genericCollection.Count < 1;
}
}

Enjoy the benefit of these extension methods.

var serverDataList = new List<ServerData>();

//It will use IsNullOrEmpty<T>(this ICollection<T> gnericCollection)
var result = serverDataList.IsNullOrEmpty();

var serverData = new ServerDataRepository().GetAll();

// It will use IsNullOrEmpty<T>(this IEnumerable<T> genericEnumerable)
var result = serverData.IsNullOrEmpty();

Can you think what it will give when I call serverDataList.Count and when I call serverData.Count?

Hint: One will give me O(n) while other O(1), enjoy!

If still confused, view this video on .NET collection by legend author, Mr. Shivprasad Koirala.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Gaurav Kumar Arora

Software Developer (Senior)

India

Gaurav thinks there is no age limit for learning and its never late, when you start.

He is an enthusiast, a good learner. Teaching & spreading technical knowledge is his passion.

You may also be interested in...

Convert Datatable to Collection using Generic

Securing Your Worklight Applications with IBM Worklight Application Scanning

Generic Collections: Interfaces & Classes

Intel® Edison Board User Guide

A Generic Tree Collection

Beyond RDBMS: A Guide To NoSQL Databases

Comments and Discussions

8 messages have been posted for this article Visit http://www.codeproject.com/Articles/1018368/IsNullOrEmpty-for-Generic-Collections-in-Csharp to post and view comments on this article, or click here to get a print view with messages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150813.1 | Last Updated 12 Aug 2015

Article Copyright 2015 by Gaurav Kumar Arora
Everything else Copyright © CodeProject, 1999-2015