1

I encountered this LINQ statement, which after some exhaustive Googling, I haven't found a comprehensive explanation:

var x = Context.TableName
               .AsNoTracking()
               .Where(x => (x.ColumnName & 2) == 2)
               .Select(x => new {col = x.Column})
               .ToList();

The part that I don't completely get is the .Where clause here.

.Where(x => (x.ColumnName & 2) == 2)

I am unsure whether that value resolves to an 'AND' clause?

Additional info: Found out that the & means the Bitwise AND operator. But how is it being applied to the value in place? For example, if the Column value is 514, it is being retrieved, but if it is 512, it is not being retrieved. I just want to understand how the bitwise is checking its applicability in the said values (514, 512).

Edit: Typo on 3 on the bitwise. Should be 2!

Chett
  • 91
  • 7

3 Answers3

2

Assuming that ColumnName is of an integer or of some other whole number type, then (x.ColumnName & 2) will do bitwise AND. Since 2 is 0000 0000 0010 in binary calculus, expression (x.ColumnName & 2) == 2 means that the value of x.ColumnName must match pattern **** **** ***1* in binary calculus.

For example, if the value of x.ColumnName is 514, then the result of (x.ColumnName & 2) will be

0010 0000 0010 (514)
&
0000 0000 0010 (2)
= 
0000 0000 0010 (2)

and the expression (x.ColumnName & 2) == 2 will return true.

If the value of x.ColumnName is 512, then the result of (x.ColumnName & 2) will be

0010 0000 0000 (512)
&
0000 0000 0010 (2)
= 
0000 0000 0000 (0)

and the expression (x.ColumnName & 2) == 2 will return false.

Unknown User
  • 78
  • 1
  • 7
1

This approach lets you test if the second least significant bit of the binary representation of x.ColumnName is set:

  • val & 2 masks off the bits other than second least significant
  • Comparison to 2 checks that bit is set to 1.

This translates to RDBMS-dependent bitwise AND operator (operator & in SQL Server).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Check this table

enter image description here

When X and Y are true only then X&Y is true. Otherwise, it's false. Number 2 in binary is 10. So, X&2 will always return 2 (in binary 10) or 0 For example:

15 & 2 = 2

1111 (15)
&
0010 (2)
= 
0010 (2)

13 & 2 = 0

1101 (13)
&
0010 (2)
= 
0000 (0)

This article is really helpful

Jack Sparrow
  • 549
  • 4
  • 13