title: Compare two enums w/bitwise for a single True result?
body: <p>How do you compare enums that have multiple bits set?  I must be missing something simple.</p>
  
  <p>I have a target persisted value of one enum, and I have the user's settings of that same enum.  I need to compare the two to see if there is a single match of one or more enum bits set.</p>
  
  <p>Bonus: I would love to use bitwise operators here to shortcut the linq query (cause I replicate this 5 or 6 times throughout different properties).  I know it's not easily readable, but it would really help performance in what I am doing.</p>
  
  <pre><code>public enum Targets
  {
    NotSet = 0,
  
    Anonymous = 1,
    Everyone = 2
    Adult = 4,
    Child = 8,
  
    LikesFishing = 16
  }
  </code></pre>
  
  <p>I have users with multiple targets set:</p>
  
  <pre><code>var loggedInUser = new User()
  {
    Username = "eduncan911",
    Targets = Targets.Everyone | Targets.Adult | Targets.LikesFishing
  };    
  </code></pre>
  
  <p>I have articles set with multiple different targets:</p>
  
  <pre><code>var article1 = new Article()
  {
    Title = "Announcement for Parents and Children",
    Targets = Targets.Adult | Targets.Child
  };
  
  var article2 = new Article()
  {
    Title = "What fishing boat do you own?",
    Targets = Targets.LikesFishing | Targets.Adult
  };
  
  var article3 = new Article()
  {
    Title = "Be nice to your parents!",
    Targets = Targets.Child
  };
  </code></pre>
  
  <p>How would I query for Articles that has 1 Target bit set that matches at least 1 Targets of the specified user above (1 or more)?  I should get back the first two articles because they match Targets.Adult - but the loggedInUser.Targets does not match any bit in the 3rd set of targets.</p>
  
  <p>I know I can query articles for a specific Enum type, like this:</p>
  
  <pre><code>var articles =
    db.Articles.Where(x =&gt; x.Targets.HasFlag(Targets.LikesFishing);
  </code></pre>
  
  <p>But, I don't have a single Target - I have multiple bits set.  Therefore, passing in just "loggedInUser.Targets" would never match any as the stored value is just an int.</p>
  
  <p>At first, I was querying for enums like this:</p>
  
  <pre><code>// returns a collection of enums the user has set
  // in their profile.
  var loggedInUserEnums =
    Enum.GetValues(typeof(Targets))
      .Cast&lt;Targets&gt;()
      .Where(x =&gt; loggedInUser.Targets.HasFlag(x));
  </code></pre>
  
  <p>But when comparing the collection to the other collection of what articles have set, I was always getting back true for every article.  I think I was going off to la-la land.</p>
  
  <p>Is there a bitwise operation I can pass into the linq expression db.Articles.Where(...) to compare the two?</p>
  
  <p>Just a guess, but I notice when I query for article targets that I have NotSet returning true as well - no matter of I ~Targets.NotSet or not.  Odd.</p>