代码之家  ›  专栏  ›  技术社区  ›  CRice

Linq Sql IQueryable<T>和链接或操作

  •  1
  • CRice  · 技术社区  · 16 年前

    我试图模拟:

    使用“和”的原因如下。。。考虑到其他过滤可能与IsActive过滤器一样涉及,我如何用iqeryable(qry)和我的nullable int模拟“OR”条件?

                if (onlyActiveItems) //bool
                {
                    qry = qry.Where(x => x.IsActive == true);
                }
    
                if (whenSpecifiedMustIncludeRecordWithThisId.HasValue) //int?
                {
                    qry = qry.Where(x => x.Id == whenSpecifiedMustIncludeRecordWithThisId.Value);
                }
    

    我曾考虑过联合,但似乎解决这个问题的办法应该简单得多。


    这是一个解决方案,它解决了我在尝试组合“一体式”答案时遇到的“可空对象必须有值”问题。当nullable为null时,是什么导致对其求值的?

                if (whenSpecifiedMustIncludeRecordWithThisId.HasValue)
                {
                    qry = qry.Where(x => (!onlyActiveItems || (onlyActiveItems && x.IsActive)) || x.Id == whenSpecifiedMustIncludeRecordWithThisId.Value);
                }
                else
                {
                    qry = qry.Where(x => (!onlyActiveItems || (onlyActiveItems && x.IsActive)));
                }
    

    在某些情况下,似乎使用nullable的.Value属性也会产生不同,正如我在这里的另一个问题中所看到的 Linq to SQL Int16 Gets Converted as Int32 In SQL Command

    2 回复  |  直到 9 年前
        1
  •  2
  •   Yannick Motton    16 年前

    试试这个:

    qry = qry.Where(x => (onlyActiveItems
                          ? x.IsActive
                          : false) ||
                         (whenSpecifiedMustIncludeRecordWithThisId.HasValue
                          ? x.Id == whenSpecifiedMustIncludeRecordWithThisId
                          : false) ||
                         (!onlyActiveItems && !whenSpecifiedMustIncludeRecordWithThisId.HasValue));
    

    请注意,我们正在比较 int? 到 int 不是两个 s

    我在这里假设查询的目的是过滤掉是否满足某些条件。

    • 如果 onlyActiveItems
    • 如果 whenSpecifiedMustIncludeRecordWithThisId.HasValue 如果为true,则验证该值是否与Id字段匹配
    • 如果两者都为真,则逻辑上或条件
        2
  •  0
  •   Clay Lenhart    16 年前

    当使用“int”时,我通常使用object.Equals(i1,i2)来比较它们

    from r in cxt.table
    where object.Equals(r.column, nullableInt)
    select r
    

    这避免了所有可为空的问题。