简体   繁体   English

如何重载Linq的Where子句以接受SqlBoolean?

[英]How do you overload Linq's Where clause to accept SqlBoolean?

Linq's Where clause works with booleans. Linq的Where子句可用于布尔值。 How do you get it to work with sqlBooleans. 如何使它与sqlBooleans一起使用。 Here is sample code to illustrate the problem 这是示例代码来说明问题

// 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

You get an error since the result of the predicate is SqlBoolean rather than bool. 由于谓词的结果是SqlBoolean而不是bool,因此会出现错误。 How do you extend the Where clause to make this work. 您如何扩展Where子句来完成这项工作。 Using casting, SqlBoolean's Value, IsTrue and IsFalse are not desirable. 使用强制转换时,不希望使用SqlBoolean的Value,IsTrue和IsFalse。

You have to convert the SqlBoolean to a bool . 您必须将SqlBoolean转换为bool You can cast it explicitly : 您可以显式转换它:

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

or compare the Value property: 或比较Value属性:

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

The problem is that SqlBoolean == SqlBoolean returns SqlBoolean not bool since the equality operator is overridden . 问题是SqlBoolean == SqlBoolean返回SqlBoolean bool因为相等运算符被覆盖

You could create an extension method to wrap the Where : 您可以创建一个扩展方法来包装Where

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

Still not the cleanest, but works: 仍然不是最干净的,但是可以工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM