Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate dynamic expression with a bitwise operator and enums?

Let's say I have the following enum.

[Flags] public enum Color { Red = 1, Blue = 2, Green = 4 }

Now, I want to use the following query to find Red shirts.

Shirts.Where(x => (x.Color & Color.Red) != 0)

And it works just fine, but when I try to construct this dynamically:

var color= Expression.Constant(Color.Red);
var property = Expression.Property(Expression.Parameter(typeof(Shirt)), "Color");
Expression.NotEqual(Expression.And(property, color), Expression.Constant(0));

I get the following exception:

The binary operator And is not defined for the types 'MyEnums.Color' and 'MyEnums.Color'.

I'm using .NET 4.5

Any thoughts?

like image 282
Ivan Milutinović Avatar asked Mar 27 '13 13:03

Ivan Milutinović


1 Answers

Try converting color and property to the underlying type using Expression.Convert first:

var color= Expression.Constant(Color.Red);
var property = Expression.Property(Expression.Parameter(typeof(Shirt)), "Color");
var colorValue = Expression.Convert(color, Enum.GetUnderlyingType(typeof(Color)));
var propertyValue = Expression.Convert(property, Enum.GetUnderlyingType(typeof(Color)));
Expression.NotEqual(Expression.And(propertyValue, colorValue), Expression.Constant(0));
like image 120
Sam Harwell Avatar answered Oct 11 '22 06:10

Sam Harwell