A simple requirement -> Count the number of emails received in the last seven days. The code seems simple enough:
void CountEmail()
{
Outlook.Explorer currExplorer = null;
Outlook.Folder folder = null;
Outlook.Items items = null;
Outlook.ContactItem contact = null;
string contactList = string.Empty;
try
{
currExplorer = Application.ActiveExplorer();
folder = (Outlook.Folder)currExplorer.CurrentFolder;
items = folder.Items;
int count = items.Count; // 10082 count
IEnumerable<Outlook.MailItem> mail = folder.Items.OfType<Outlook.MailItem>().Where(m => m.ReceivedTime <= DateTime.Now - new TimeSpan(7, 0, 0, 0)).Select(m => m);
int itemscount = mail.Count<Outlook.MailItem>(); // out of memory here
.....
The query in mail = ... is clearly a lazy load, as no time is spent doing the work. The subsequent call is the execution, and I run out or memory. I do not want the actual content, just the count.
So, how to obtain the count of the emails received within the last seven days?