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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With