-2

The basis of the problem is that I have Ids stored in these two expressions and I need to search an array for their objects with these Ids so I can compare these two expressions based on Text.

I have this code

Expression firstExpression; //it has a value which is dynamically set during runtime  
Expression secondExpression; //it has a value which is dynamically set during runtime                     
BinaryExpression operator = BinaryExpression.Equal;                                                       
Enumerable items =  [{Id: 1, Text: "hello"}, {Id: 2, Text: "hello"}] // array of objects with ids and texts

I tried these combinations and they didnt return correctly.

var item = items.SingleOrDefault(x => firstExpression == Constant.Expression(x).Value);    

// resulting sql looks something like this SingleOrDefault(x => item.Variable == x.Value);   
                   
var item = items.SingleOrDefault(x => Constant.Expression(firstExpression) == Constant.Expression(x).Value); 
                                                                                                                      
var item = items.SingleOrDefault(x => Constant.Expression(firstExpression).Value == Constant.Expression(x).Value);

The end result should look something like:

Expression.MakeBinary(operator, Expression.Constant(item), Expression.Constant(secondItem))

I also tried compiling and invoking the expression then I just received an error that a variable is out of scope,

firstExpression.Compile().DynamicInvoke();

Because the expression variable is dynamic i dont think i can compile it but Im not sure

if you have any idea how would you retrieve this value, or maybe do this somehow differently.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Kasacko
  • 1
  • 1
  • Take a moment to read through the [editing help](/editing-help) in the help center. Formatting on Stack Overflow is different than on other sites. The better your post looks, the easier it is for others to read and understand it. – gunr2171 Aug 10 '23 at 20:08
  • Does the line that starts `Enumerable items` compile? – Flydog57 Aug 10 '23 at 20:13
  • Are you trying to evaluate an expression and access the result? If so, see this link: https://stackoverflow.com/questions/56580598/c-sharp-evaluate-a-string-expression-and-return-the-result – SoftwareDveloper Aug 10 '23 at 20:15
  • @Flydog57 that was just quick pseudocode – Kasacko Aug 10 '23 at 20:18

0 Answers0