199

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#?

anhoppe
  • 4,287
  • 3
  • 46
  • 58
lakshganga
  • 2,355
  • 6
  • 21
  • 22

8 Answers8

206

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;
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
104

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.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
  • 20
    As quick note: list.Any has much better performance than count. – Adrian Lopez Oct 28 '15 at 09:58
  • 3
    @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: https://stackoverflow.com/questions/305092/which-method-performs-better-any-vs-count-0 or https://stackoverflow.com/questions/5741617/listt-any-or-count?noredirect=1&lq=1 – noox Apr 21 '19 at 22:48
  • 3
    @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. – NetMage Nov 12 '19 at 19:38
42
    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.

Kuzgun
  • 4,649
  • 4
  • 34
  • 48
  • 1
    @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.Count`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.count?view=netframework-4.8). – Spencer Wieczorek Nov 12 '19 at 03:47
  • 2
    @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`. – NetMage Nov 12 '19 at 19:40
26

What about using the Count property.

 if(listOfObjects.Count != 0)
 {
     ShowGrid();
     HideError();
 }
 else
 {
     HideGrid();
     ShowError();
 }
lue
  • 449
  • 5
  • 16
Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
11

You should use a simple IF statement

List<String> data = GetData();

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

PopulateGrid();
ShowGrid();
Moslem Ben Dhaou
  • 6,897
  • 8
  • 62
  • 93
  • Simplest and best way IMO. – Jabba Apr 05 '18 at 11:09
  • 1
    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) ....." – daviesdoesit Mar 13 '19 at 15:27
  • 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 stringList = null; if (stringList.Count == 0) { Console.WriteLine("no items in collection"); } } } ` – daviesdoesit Mar 13 '19 at 15:30
  • @daviesdoesit that would be beyond the scope of the question. This snippet clearly assumes `data` is defined. – Moslem Ben Dhaou Sep 21 '20 at 10:03
8
var dataSource = lst!=null && lst.Any() ? lst : null;
// bind dataSource to gird source
TalentTuner
  • 17,262
  • 5
  • 38
  • 63
4

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

Baahubali
  • 4,604
  • 6
  • 33
  • 72
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>
David MacCrimmon
  • 966
  • 1
  • 6
  • 19