Check if list is empty in C# [closed]

2019-01-22 05:49发布

问题:

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

回答1:

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> 


回答2:

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:

    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.



回答4:

What about using the Count() method.

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


回答5:

You should use a simple IF statement

List<String> data = GetData();

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

PopulateGrid();
ShowGrid();


回答6:

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


回答7:

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



回答8:

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>