找不到 IEnumerable<> 的任何方法来进行空检查

Cannot find Any method of IEnumerable<> to do empty check

我有一个返回 IEnumerable<Data> 的方法,我想检查 IEnumerable 是否为 null/empty。我做了一些研究,看起来我们可以使用它的 Any 方法,但在我的代码中我没有看到任何 Any 方法,所以这意味着我是 运行 的旧版本.Net?

现在我正在使用上面的方法如下 -

private bool Process()
{
    IEnumerable<Data> dataValue = GetData();
    // check if dataValue is null or empty
    if(dataValue != null) {
        // process entry
    }
}

在我的情况下,如何检查 IEnumerable 是否为 null 或空?

更新

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
    }
}

通常

dataValue != null && dataValue.Any()

您可能需要添加 using System.Linq;

您也可以使用

if (dataValue?.Any()==true)
{}

我希望你能说

if(dataValue?.Any())

但这不会编译:-)

不需要 显式 Any 检查或 null 检查。

foreach (var x in (dataValue ?? Enumerable.Empty<Data>()))

是我的建议,因为它避免了使用 Any 的双重枚举问题(并且它将 null 视为等同于空)。所以这可能看起来像:

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;
}