title: EWS get count of unread emails from all folders
body: <p>I'm trying to get number of unread emails from Exchange for specific user.</p>
  
  <p>I'm able to get number of emails from Inbox like so:</p>
  
  <pre><code>SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
  ItemView view = new ItemView(int.MaxValue);
  FindItemsResults&lt;Item&gt; findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);
  int unreadCount = 0;
  foreach (EmailMessage i in findResults)
      {
          unreadCount++;
      }
  label1.Text = unreadCount.ToString();
  </code></pre>
  
  <p>This works great.<br>
  I'm also able to get all subfolders is Inbox:</p>
  
  <pre><code>FindFoldersResults findResults1 = service.FindFolders(
      WellKnownFolderName.Inbox,
      new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep });
  
  foreach (Folder folder in findResults1.Folders)
  {
      Console.WriteLine(folder.DisplayName);
  }
  </code></pre>
  
  <p>Problem is that I'm not able to combine these two together.<br>
  <strong>I know that I can do nested foreach loop, but I would like to avoid that.</strong></p>
  
  <p>I found these question: <a href="https://stackoverflow.com/questions/7401080/exchange-web-services-ews-finditems-within-all-folders">Exchange Web Services (EWS) FindItems within All Folders</a>, but it requires to at least use Outlook 2010 in order to create <code>AllItems</code> folder.</p>
  
  <p>I know that I can create <code>SearchFilterCollection</code>, but how to add rules to it so that it will search for unread emails in Inbox and all subfolders?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>This what I have tried to do so far:</p>
  
  <pre><code>private int getEmailCount()
  {
      int unreadCount = 0;
  
      FolderView viewFolders = new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep, PropertySet = new PropertySet(BasePropertySet.IdOnly) };
      ItemView viewEmails = new ItemView(int.MaxValue) { PropertySet = new PropertySet(BasePropertySet.IdOnly) };
      SearchFilter unreadFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
  
      FindItemsResults&lt;Item&gt; findResults = service.FindItems(WellKnownFolderName.Inbox, unreadFilter, viewEmails);
      unreadCount += findResults.Count();
  
      FindFoldersResults inboxFolders = service.FindFolders(WellKnownFolderName.Inbox, viewFolders);
  
      foreach (Folder folder in inboxFolders.Folders)
      {
          findResults = service.FindItems(folder.Id, unreadFilter, viewEmails);
          unreadCount += findResults.Count();
      }
  
      return unreadCount;
      }
  </code></pre>
  
  <p>Basically this works, but when I have created multiple subfolders it started to work very slow.<br>
  <strong>Instead of multiple queries can I do one to get same results?</strong></p>