【问题标题】:How do you overload Linq's Where clause to accept SqlBoolean?如何重载 Linq 的 Where 子句以接受 SqlBoolean?
【发布时间】:2014-09-07 15:42:01
【问题描述】:

Linq 的 Where 子句适用于布尔值。你如何让它与 sqlBooleans 一起工作。这是说明问题的示例代码

// Trivia example to draw attention to the problem 
var nodeCollection = new List<SqlBoolean>();
nodeCollection.Add(SqlBoolean.Parse("0"));
nodeCollection.Add(SqlBoolean.Parse("1"));
nodeCollection.Add(SqlBoolean.Parse("1"));

var nodeA = SqlBoolean.Parse("1");
var trueOne = nodeCollection.Where(n => n == nodeA); // Error message, cannot convert SqlBoolean to bool

你得到一个错误,因为谓词的结果是 SqlBoolean 而不是 bool。您如何扩展 Where 子句以使其工作。使用强制转换,SqlBoolean 的 Value、IsTrue 和 IsFalse 是不可取的。

【问题讨论】:

    标签: c# .net linq boolean linq-to-objects


    【解决方案1】:

    您必须将SqlBoolean 转换为bool。你可以投explicitly:

    var trueOne = nodeCollection.Where(n => (bool)(n == nodeA));  
    

    或比较Value 属性:

    var trueOne = nodeCollection.Where(n => n.Value == nodeA.Value); 
    

    问题是SqlBoolean == SqlBoolean 返回SqlBoolean 而不是bool,因为equality operator is overridden

    【讨论】:

    • 是的。但是,我需要它而不需要演员。
    • 如果运算符被覆盖,那么恐怕你不能不强制转换\使用nodaA.Value...
    • 哦。 Sergey,这对于覆盖来说是正确的,但是重载呢?
    • SqlBoolean 是一个struct,所以你不能继承它和重载方法....你可以用重载的 == 运算符围绕SqlBoolean 创建一些包装类,但不确定这将是一个好方法
    • @SergeyLitvinov。多谢你们。你说得很好,但我对这个问题的思考不够深入。
    【解决方案2】:

    您可以创建一个扩展方法来包装Where

    public static IEnumerable<T> WhereSqlBoolean<T>(
        this IEnumerable<T> source, Func<T,SqlBoolean> condition) {
        return source.Where(t => (bool)condition(t));
    }
    

    仍然不是最干净的,但有效:

    var trueOne = nodeCollection.WhereSqlBoolean(n => n == nodeA);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多