Check if list is empty in C#

lakshganga picture lakshganga · Sep 18, 2013 · Viewed 362.5k times · Source

I have a list of objects populated from a database. I need to display an error message if the list is empty and display a grid view otherwise.

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

Answer

Tim Schmelter picture Tim Schmelter · Sep 18, 2013

Why not...

bool isEmpty = !list.Any();
if(isEmpty)
{
    // error message
}
else
{
    // show grid
}

The GridView has also an EmptyDataTemplate which is shown if the datasource is empty. This is an approach in ASP.NET:

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

<emptydatatemplate>

  <asp:image id="NoDataErrorImg"
    imageurl="~/images/NoDataError.jpg" runat="server"/>

    No Data Found!  

</emptydatatemplate>