Check if list is empty in C#

C#ListIsnullorempty

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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;

Solution 2 - C#

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.

Solution 3 - C#

    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.

Solution 4 - C#

What about using the Count property.

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

Solution 5 - C#

You should use a simple IF statement

List<String> data = GetData();

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

PopulateGrid();
ShowGrid();

Solution 6 - C#

var dataSource = lst!=null && lst.Any() ? lst : null;
// bind dataSource to gird source

Solution 7 - C#

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

Solution 8 - C#

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlakshgangaView Question on Stackoverflow
Solution 1 - C#Tim SchmelterView Answer on Stackoverflow
Solution 2 - C#Grant ThomasView Answer on Stackoverflow
Solution 3 - C#KuzgunView Answer on Stackoverflow
Solution 4 - C#Jeroen van LangenView Answer on Stackoverflow
Solution 5 - C#Moslem Ben DhaouView Answer on Stackoverflow
Solution 6 - C#TalentTunerView Answer on Stackoverflow
Solution 7 - C#BaahubaliView Answer on Stackoverflow
Solution 8 - C#David MacCrimmonView Answer on Stackoverflow