Linq's Where clause works with booleans. How do you get it to work with 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. How do you extend the Where clause to make this work. Using casting, SqlBoolean's Value, IsTrue and IsFalse are not desirable.
You have to convert the SqlBoolean
to a bool
. You can cast it explicitly :
var trueOne = nodeCollection.Where(n => (bool)(n == nodeA));
or compare the Value
property:
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 .
You could create an extension method to wrap the 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.