title: How to use MongoDB's Query and QueryBuilder in c# foreach loop?
body: <p>I am trying to query my collections but I'm not sure how to do an "append" of sorts to <code>Query.And()</code></p>
  
  <p>Here is my domain model to create the <code>Item</code> document:</p>
  
  <pre><code>public class Item
  {
      public ObjectId Id { get; set; }
      public string ItemTypeTemplate { get; set; }
      public string UsernameOwner { get; set; }
  
      public IList&lt;ItemAttribute&gt; Attributes { get; set; }
  }
  </code></pre>
  
  <p>The <code>IList&lt;ItemAttribute&gt;</code> collection changes depending on <code>ItemTypeTemplate</code> (some sort of a lookup key to a pre-determined list of an item's attributes)</p>
  
  <p>Here is a sample of an <code>Item</code> document:</p>
  
  <pre><code>{
      "_id" : ObjectId("5130f9a677e23b11503fee72"),
      "ItemTypeTemplate" : "Tablet Screens", 
           //can be other types like "Batteries", etc.
           //which would change the attributes list and values
      "UsernameOwner" : "user032186511",
       "Attributes" : [{
           "AttributeName" : "Screen Size",
           "AttributeValue" : "10.1"
       }, {
           "AttributeName" : "Pixel Density",
           "AttributeValue" : "340"
       }]
  }
  </code></pre>
  
  <p><strong>THE PROBLEM</strong> </p>
  
  <p>Given the "dynamic" nature of <code>IList&lt;ItemAttribute&gt;</code>, I cannot manually specify the additional query conditions for <code>AttributeName</code> and <code>AttributeValue</code> so I thought of using a loop to build the query:</p>
  
  <pre><code>QueryBuilder&lt;Item&gt; qbAttributes = new QueryBuilder&lt;Item&gt;();
  
  foreach (var attribute in item.Attributes)
  {
      qbAttributes.And(
          Query.EQ("Attributes.AttributeName", attribute.AttributeName),
          Query.EQ("Attributes.AttributeValue", attribute.AttributeValue),
      );
  }
  
  var query = Query.And(
      Query.EQ("TemplateId", item.TemplateId),
      Query.NE("UsernameOwner", item.UsernameOwner)
  );
  
  return DBContext.GetCollection&lt;Item&gt;("Items").Find(query).AsQueryable();
  </code></pre>
  
  <p>How do I "append" <code>qbAttributes</code> to <code>query</code>? I tried <code>qbAttributes.And(query);</code> but <code>.Find(query)</code> errors out with an invalid argument.</p>
  
  <p>I need something that would be like:</p>
  
  <pre><code>var query = Query.And(
      Query.EQ("ItemTypeTemplate", item.ItemTypeTemplate),       //Tablet Screens
      Query.NE("UsernameOwner", item.UsernameOwner)              //current user
  
      // this part is generated by the loop
  
      Query.EQ("Attributes.AttributeName", "Screen Size"),
      Query.EQ("Attributes.AttributeValue", "10.1"),
  
      Query.EQ("Attributes.AttributeName", "Pixel Density"),
      Query.EQ("Attributes.AttributeValue", "340")
  );
  </code></pre>