I have used the single ampersand (&) in C# to mean "check the second conditional statement even if the first is false".
But the following seems to be a different meaning of &
altogether, can anyone explain how i & 1
works in the following example?
List<int> scores = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8 };
var evenScores = scores.Where(i => i % 2 == 0);
var evenScores2 = scores.Where(i => (i & 1) == 0);
A single & is "Bitwise AND operator", just like dove said. I'm looking at second part of question: "why it works?"
Think in binary:
000 = 0
001 = 1
010 = 2
011 = 3
100 = 4
101 = 5
110 = 6
111 = 7
and so on
Note all even numbers ends with 0; so if last bit bitwise check against 1 returns zero (meaning "doesn't match"), its a even number;