我有个前程环。
foreach(var item in dataGrid)
{
}我需要判断" item“是否为null,因为当项目为null时,我会得到一个NullReferenceException。注意:我的目的不是判断"dataGrid",因为出于某些原因,我的程序中的这个"dataGrid“永远都不是空的(它的值是1,当它实际上是空的或1),但是当"dataGrid”实际上是空的时候,“dataGrid”可以是空的。
实际问题-如何判断项目是否为null?
发布于 2014-08-27 08:16:26
可以使用Where消除空项。
foreach(var item in dataGrid.Where(x => x != null))发布于 2014-08-27 08:16:47
foreach(var item in dataGrid)
{
if(item == null) continue;
// do your work here...
}发布于 2014-08-27 08:16:19
您可以简单地使用for each循环中的IF语句来检查它。
foreach(var item in dataGrid) {
if (item == null) {
// Do something, throw exception, continue, whatever...
} else {
// Do something useful with item...
}
}https://stackoverflow.com/questions/25522068
复制相似问题