检查 C# 中的列表是否为空
本文关键字:是否 列表 检查 | 更新日期: 2023-09-27 18:31:57
>我有一个通用列表对象。我需要检查列表是否为空。
如何检查 C# 中的List<T>
是否为空?
您可以使用
Enumerable.Any
:
bool isEmpty = !list.Any();
if(isEmpty)
{
// ...
}
如果列表可以null
您可以使用:
bool isNullOrEmpty = list?.Any() != true;
如果您使用的列表实现是IEnumerable<T>
并且 Linq 是一个选项,则可以使用 Any
if (!list.Any()) {
}
否则,您通常分别对数组和集合类型具有 Length
或 Count
属性。
If (list.Count==0){
//you can show your error messages here
} else {
//here comes your datagridview databind
}
你可以使数据网格可见 false,并使其在 else 部分可见。
使用 Count
属性怎么样?
if(listOfObjects.Count != 0)
{
ShowGrid();
HideError();
}
else
{
HideGrid();
ShowError();
}
你应该使用一个简单的IF
语句
List<String> data = GetData();
if (data.Count == 0)
throw new Exception("Data Empty!");
PopulateGrid();
ShowGrid();
var dataSource = lst!=null && lst.Any() ? lst : null;
// bind dataSource to gird source
gridview 本身有一个方法,可以检查您绑定到的数据源是否为空,它允许您显示其他内容。
如果您使用的是网格视图,请使用空数据模板: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>