You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用LINQ优雅检查分组字符串数组中是否存在IsNullOrEmpty元素?

问题

我已经实现了对多个字符串数组分组,并且完成了检查所有数组长度一致、无空数组的逻辑,具体代码如下:

//Create arrays by comma delimiter
string[] woptelwosoitemno_List = !string.IsNullOrEmpty(distinct_WO_Parts_Row.Wop__tel_wo_soitemno) ? 
                                   distinct_WO_Parts_Row.Wop__tel_wo_soitemno.Split(',') : null;
string[] woptelwosoiteminstalledqty_List= !string.IsNullOrEmpty(distinct_WO_Parts_Row.Wop__tel_wo_soiteminstalledqty) ? 
                                   distinct_WO_Parts_Row.Wop__tel_wo_soiteminstalledqty.Split(',') : null;

//Group all arrays
string[][] allArrays = new string[][] { woptelwosoitemno_List, woptelwosoiteminstalledqty_List};

//Check all array length are the same
var arrayLength = allArrays.GroupBy(x => x.Length);

//Check all arrays are not null
var arrayNull = allArrays.GroupBy(x => x == null);

现在需要检查所有数组中的任意元素是否为IsNullOrEmpty,但当前逐个数组判断的方式不够优雅(如下代码),想找更简洁的实现方式:

if ((woptelwosoitemno_List.Any(a => String.IsNullOrEmpty(a)))
     || (woptelwosoiteminstalledqty_List.Any(a => String.IsNullOrEmpty(a))))
解决方案

直接用已有的allArrays二维数组,通过两层LINQ就能一次性完成检查,不用逐个写数组变量,代码更简洁,后续新增数组也只需加到allArrays里就行:

bool hasNullOrEmptyElement = allArrays.Any(arr => arr.Any(element => string.IsNullOrEmpty(element)));

if (hasNullOrEmptyElement)
{
    // 这里写存在空元素的处理逻辑
}

逻辑说明

  • 外层Any(arr => ...)遍历allArrays里的每一个子数组
  • 内层Any(element => ...)检查当前子数组里有没有空或者空字符串的元素
  • 只要有任意一个子数组里存在符合条件的元素,整个表达式就返回true

要是担心子数组可能为null(虽然你已经做了空数组检查),可以先过滤掉null数组再检查,避免空引用异常:

bool hasNullOrEmptyElement = allArrays.Where(arr => arr != null)
                                      .Any(arr => arr.Any(element => string.IsNullOrEmpty(element)));

内容的提问来源于stack exchange,提问作者gymcode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 20:40:36