213

I have a generic list object. I need to check if the list is empty.

How do I check if a List<T> is empty in C#?

3
  • 13
    So what's wrong with using if (list.Count == 0) { /* ... */ }? Commented Sep 18, 2013 at 8:27
  • 17
    Or if (!list.Any()) Commented Sep 18, 2013 at 8:30
  • 2
    This: stackoverflow.com/q/8582344/492 Commented Aug 1, 2014 at 9:11

10 Answers 10

223

You can use Enumerable.Any:

bool isEmpty = !list.Any();
if(isEmpty)
{
    // ...
}  

If the list could be null you could use:

bool isNullOrEmpty = list?.Any() != true;
Sign up to request clarification or add additional context in comments.

4 Comments

Would it not be best to check whether list == null first?
@ᴍᴀᴛᴛʙᴀᴋᴇʀ, var someList = new List<string>(); would be instantiated( and therefore not be null) but would be empty of elements to process
@ruffin: especially the "clearer" is doubtful: "To determine whether a collection type has any elements, it's clearer to use the Length, Count...". So dont use Any if you want to determine if something has any elements, because it's unclear, better check if the total count or length is greater than 0. Funny
107

If the list implementation you're using is IEnumerable<T> and Linq is an option, you can use Any:

if (!list.Any()) {

}

Otherwise you generally have a Length or Count property on arrays and collection types respectively.

3 Comments

As quick note: list.Any has much better performance than count.
@AdrianLopez: can you elaborate on that? If you have a .Count or .Length property as with List what could .Any() possibly do to be faster than checking the property of the collection which keeps track of the the current length or count? If you only have an Enumerator, then .Any() is of course faster than .Count() > 0. See also: stackoverflow.com/questions/305092/… or stackoverflow.com/questions/5741617/…
@noox Looking at the (.Net Core) source, it seems Any checks to validate that retrieving the count is cheap before testing it, in cases where you have an IListProvider<> that doesn't track the count, it will enumerate once instead.
45
    If (list.Count==0){
      //you can show your error messages here
    } else {
      //here comes your datagridview databind 
    }

You can make your datagrid visible false and make it visible on the else section.

2 Comments

@NetMage That's not how it works for list. It's an O(1) operation and there is no iterations done for counting elements. See List<T>.Count.
@SpencerWieczorek You are correct, that comment was old as well as wrong :) Though in general, I would still prefer Any() as expressing intent better, as well as being more performant when you don't know you have an actual List<T>.
27

What about using the Count property.

 if(listOfObjects.Count != 0)
 {
     ShowGrid();
     HideError();
 }
 else
 {
     HideGrid();
     ShowError();
 }

5 Comments

Count is a property not a method
@MoslemBenDhaou Depends on whether it's the Linq extension method exposed/being called, or native to the object.
@GrantThomas I took it as a List<T> object but yes you are correct.
what if listOfObjects is null?
@SabriMeviş a collection/ienumerable/list returned from a method should never be null. It should be an empty collection instead.
11

You should use a simple IF statement

List<String> data = GetData();

if (data.Count == 0)
    throw new Exception("Data Empty!");

PopulateGrid();
ShowGrid();

4 Comments

Simplest and best way IMO.
If the method returns a null, the Count property will fail. To keep the code concise, consider the null reference check operator "?". Example "if (data?.Count == 0) . . . . ." or the classic null check "if (data != null && someOtherCondition) ....."
Paste the following code into a dotnetfiddle and you'll see the System.NullReferenceException: Object reference not set to an instance of an object. using System; using System.Collections.Generic; public class Program { public static void Main() { List<string> stringList = null; if (stringList.Count == 0) { Console.WriteLine("no items in collection"); } } }
@daviesdoesit that would be beyond the scope of the question. This snippet clearly assumes data is defined.
8
var dataSource = lst!=null && lst.Any() ? lst : null;
// bind dataSource to gird source

Comments

4

gridview itself has a method that checks if the datasource you are binding it to is empty, it lets you display something else.

Comments

3

Some of the answers above recommend using list.Any() and some of them recommend using list.Count > 0.

When using .Any() on a List, Visual Studio shows the following warning: CA1860: Prefer comparing 'Count' to 0 rather than using 'Any()', both for clarity and for performance

If you check the respective rule code CA1860 Microsoft recommends to "Avoid using 'Enumerable.Any()' extension method".

Therefore using list.Count > 0 is recommended over using list.Any()

7 Comments

Could not reproduce this CA1860 error. Please add some code which allows me to reproduce this. (see: dotnetfiddle.net/pMQlLW )
@Luuk Even if you can't reproduce CA1860, you can still take a look at the resource I provided. I edited my answer to contain the version of Visual Studio I am using.
@Luuk If I copy the code you provided in your dotnetfiddle to my Visual Studio, I see the warning I mentioned in my answer.
@Luuk You should see three dots under list in the code you showed in VS2022. If you hover the cursor over list.Any you'll see a box pop up with the CA1860 message at the bottom.
@AndrewMorton: Sorry, I am too new to C# to be bothered by those three dots, so I ignored them (until now!).
|
1

If you're using a gridview then use the empty data template: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatemplate.aspx

      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="true"
        runat="server">

        <emptydatarowstyle backcolor="LightBlue"
          forecolor="Red"/>

        <emptydatatemplate>

          <asp:image id="NoDataImage"
            imageurl="~/images/Image.jpg"
            alternatetext="No Image" 
            runat="server"/>

            No Data Found.  

        </emptydatatemplate> 

      </asp:gridview>

2 Comments

This is very ASP.NET specific.
I'm not a winforms guys but isn't a gridview asp.net specific. It's a datagridview in forms?
-1

Sometimes you need to force rerender parent component when you don't have a direct access to this parent component. Then you can use:

this.$parent.$forceUpdate();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.