Reputation: 35
I have a foreach loop.
foreach(var item in dataGrid)
{
}
I need to judge if "item" is null, because when the item is null, i get a NullReferenceException. NOTE: my purpose is not to judge "dataGrid", because for some reasons, this "dataGrid" in my program is never null (its value is 1 when it is actually null or 1), but "item" can be null when "dataGrid" is acutally null.
The actual question - How to judge whether item is null?
Upvotes: 0
Views: 198
Reputation: 2646
foreach(var item in dataGrid)
{
if(item == null) continue;
// do your work here...
}
Upvotes: 1
Reputation: 101681
You can eliminate null items using Where
:
foreach(var item in dataGrid.Where(x => x != null))
Upvotes: 6
Reputation: 22945
You can simply check it using an IF statement inside the for each loop.
foreach(var item in dataGrid) {
if (item == null) {
// Do something, throw exception, continue, whatever...
} else {
// Do something useful with item...
}
}
Upvotes: 0