0

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?

JamieMeyer
  • 386
  • 3
  • 14

1 Answers1

1

Don't ever use LINQ with COM - it looks cool in your code, but it is horrible from the performance point of view. Not to mention that you can run out of RPC channels in the online mode.

Use Items.Find/FindNext or Items.Restrict.

Dmitry Streblechenko
  • 62,942
  • 4
  • 53
  • 78
  • I am aware of the .Restrict, but the Msft docs are really lacking here. I found another SO post that helped in case others are having this issue as well; http://stackoverflow.com/questions/17169646/microsoft-office-interop-outlook-items-restrict-not-working-correctly – JamieMeyer Apr 02 '16 at 18:41