【问题标题】:Ignore Null and Empty string match in Linq Query忽略 Linq 查询中的 Null 和空字符串匹配
【发布时间】:2024-05-02 05:20:05
【问题描述】:

如何在执行以下查询时忽略 NULL 和空字符串匹配?

var tMisMatchList = lstExchgMatch.Any(o =>
    o.MulDivFlg != lstExchgMatch[0].MulDivFlg); 

例如,列表有以下数据

  [0] = MulDivFlg = "";     // 1st element in the list whose multdivflag value is ""
  [1] = MulDivFlg = null; // 2nd element in the list whose multdivflag value is null
  [2] = MulDivFlg = null; 
  [3] = MulDivFlg = ""; 

在这种情况下,我上面的查询返回 true。因为“”和 NULL 不匹配已经发生。但我的期望是忽略 null 和 "" 比较检查。它只会执行不可为空和非空字符串匹配。它应该忽略 null 和 "" 的存在并将两者视为相等

上面的查询返回 false,因为它认为 null 不等于 ""。 但我希望它返回 true 并在字符串为 null 或 "" 时将 null 和 "" 视为相等或忽略。

【问题讨论】:

  • 请添加现在的结果是什么以及您希望收到什么结果
  • this
  • 用预期的输出@S.Petrosov 更新了我的问题

标签: c# .net linq


【解决方案1】:

您可以在 Any lambda 表达式中添加 && (string.IsNullOrEmpty(o.MulDivFlg) != string.IsNullOrEmpty(lstExchgMatch[0].MulDivFlg)) 条件:

var tMisMatchList = lstExchgMatch.Any(o => o.MulDivFlg != lstExchgMatch[0].MulDivFlg &&
    (string.IsNullOrEmpty(o.MulDivFlg) != string.IsNullOrEmpty(lstExchgMatch[0].MulDivFlg))); 

【讨论】:

    最近更新 更多