# LINQ to SQL Dynamic Expression API

bit-manipulation c# dynamic-linq enumeration linq-to-sql ### Question

We are using the DynamicLinq.cs class and are attempting to set the where clause of our query to check bitwise data values.

Enumeration example (has Flags Attribute on the enumeration):

``````None = 0

Flag1 = 1

Flag2 = 2

Flag3 = 4
``````

What we specifically want to achieve is to return data excluding â€˜Flag1â€™ values i.e. exclude resolved values of 1, 3, 5 & 7. I believe that in standard LINQ you can achieve this by using something like â€œ& ~â€ but we just canâ€™t seem to get the Dynamic Expression API to accept what we are doing, the parsing of the resultant query will always fail.

Does anyone know how to manipulate and work with bitwise enumerations in the Dynamic Expression API?

1
1
3/6/2014 9:05:13 AM

#### Fastest Entity Framework Extensions

It looks like Dynamic LINQ does not support the bit-wise operations. You can get around by using this equivalent mathematical formula for the bitwise operations:

``````(a & 2^n == 0) <==> a % 2^(n+1) < 2^n
``````

The Dynamic LINQ library does support the mod operator (`%`), so you can accomplish this:

``````Where("MyFlag % 2 < 1")
``````

Basically how this works. Suppose you want to find all values that exclude `Flag3`. Since `Flag3 = 4`, that is `4 = 2^2`, so `n=2`. The standard way of writing this would be (`MyFlagValue & Flag3 == 0`), that is, when you bitwise `and` with `Flag3`, you should get 0, representing the flag is not included.

This can also be expressed mathematically without using any bit-wise operators by grabbing the right-most 3 bits (by applying `% 8`), and checking if the value is less than `4`, which would be the value if the 3-from-right bit is not set. So for example, with `MyFlagValue=14`

``````MyFlagValue =         14 = 0b1110
MyFlagValue % 8 =      6 = 0b0110
MyFlagValue % 8 < 4 =  false  ^ which means 3-from-right bit (Flag3) is set
``````

Another example, where `MyFlagValue=58`:

``````MyFlagValue =         58 = 0b111010
MyFlagValue % 8 =      2 = 0b000010
MyFlagValue % 8 < 4 =  true     ^ which means 3-from-right bit (Flag3) is NOT set
``````

So this can be expressed in a mathematical way that is understood by Dynamic LINQ to check if the third flag `Flag3` is NOT set:

``````Where("MyFlagValue % 8 < 4")
``````
3
4/17/2012 3:28:04 PM

Prime Library

More Projects...