Change the condition in LINQ to another condition
I have two LINQ lines that differ from each other in only one condition.
node.Image.Tag == null
and node.Image.Tag != null
if (treeSelectedNode.Image.Tag == null)
{
radNode = tree.Find(node => node.Level == 0 && node.Image.Tag == null
&& node.Text.Equals(treeSelectedNode.Text));
}
else
{
radNode = tree.Find(node => node.Level == 0 && node.Image.Tag != null
&& node.Text.Equals(treeSelectedNode.Text));
}
Is there a way to create a condition before the LINQ line and then use that so I can remove the extra line?
I know I can do something like this:
radNode = treeSelectedNode.Image.Tag == null ? tree.Find(node => node.Level == 0
&& node.Image.Tag == null && node.Text.Equals(treeSelectedNode.Text)) :
tree.Find(node => node.Level == 0 && node.Image.Tag != null
&& node.Text.Equals(treeSelectedNode.Text));
But that's just not what I want.
source to share
Check that the result of the condition node.Image.Tag == null
is the same as the result treeSelected.Image.Tag == null
:
radNode = tree.Find(node => node.Level == 0 && ((node.Image.Tag == null) == (treeSelectedNode.Image.Tag == null))
&& node.Text.Equals(treeSelectedNode.Text))
Update
Addressing @KhanTo's problem concerns in particular:
Boolean selectedImgTagIsNull = treeSelected.Image.Tag == null;
radNode = tree.Find(node => node.Level == 0 && ((node.Image.Tag == null) == selectedImgTagIsNull)
&& node.Text.Equals(treeSelectedNode.Text))
However, I suspect that JIT optimizations will have a high likelihood of doing the same even for my source code.
source to share
Technically you can build a query like this with Expression, it needs some extra work, here's a simple example:
private static Expression<Func<T, bool>> AndCombined<T>(Expression<Func<T, bool>> exp1, Expression<Func<T, bool>> exp2)
{
ParameterExpression p = exp1.Parameters.Single();
return Expression.Lambda<Func<T, bool>>(Expression.And(exp1.Body, Expression.Invoke(exp2, p)), exp1.Parameters.Single());
}
static void Main(string[] args)
{
var b = new List<int>() { 30, 15, 5 };
Expression<Func<int, bool>> test1 = f => f > 10;
Expression<Func<int, bool>> test2 = f => f < 20;
var combinedAndQuery = AndCombined(test1, test2);
var reuslt1 = b.Find(new Predicate<int>(combinedAndQuery.Compile()));
Expression<Func<int, bool>> test3 = f => f < 40;
var combinedAndQuery2 = AndCombined(test1, test3);
var reuslt2 = b.Find(new Predicate<int>(combinedAndQuery2.Compile()));
}
source to share