I have a method where I am returning IEnumerable<Data>
and I wanted to check whether IEnumerable
is null/empty or not. I did some research and it looks like we can use Any
method of it but in my code I don't see any Any
method in it so that means I am running older version of .Net?
Now I am using above method as below -
private bool Process()
{
IEnumerable<Data> dataValue = GetData();
// check if dataValue is null or empty
if(dataValue != null) {
// process entry
}
}
What can I do to check if IEnumerable
is null or empty in my case?
Update
private bool Process()
{
IEnumerable<Data> dataValue = GetData();
if(dataValue = null || !dataValue.Any()) {
return false;
}
foreach (var x in dataValue)
{
// iterating over dataValue here and extracting each field of Data class
}
}
There is no need for an explicit Any
check or null
check.
foreach (var x in (dataValue ?? Enumerable.Empty<Data>()))
is what I would suggest, since it avoids the double enumeration problem of using Any
(and it treats null
as equivalent to empty). So this might look like:
private bool Process()
{
bool returnValue = false;
IEnumerable<Data> dataValue = GetData();
foreach (var x in (dataValue ?? Enumerable.Empty<Data>()))
{
returnValue = true;
// iterating over dataValue here and extracting each field of Data class
}
return returnValue;
}