在c#中测试'lazy loaded'null IEnumerable?

max*_*axp 7 c# linq ienumerable

我已经简化了一段延迟执行代码,但是你怎么检查以下不是null/empty而不将它包装在try/catch中?

    string[] nullCollection = null;
    IEnumerable<string> ienumerable = new[] { nullCollection }.SelectMany(a => a);

    bool isnull = ienumerable == null; //returns false
    bool isany = ienumerable.Any(); //throws an exception
Run Code Online (Sandbox Code Playgroud)

RB.*_*RB. 3

您只需要让您的 lambda 更能适应 null 条目:

IEnumerable<string> ienumerable = new[] { nullCollection }
    .SelectMany(a => a ?? Enumerable.Empty<string>());

bool isany = ienumerable.Any(); // Sets isany to 'false'
Run Code Online (Sandbox Code Playgroud)