'Outlook.Items Restrict() weird behavior

I just want to filter my Mails with the Restrict-Method like so:

            restriction += "[ReceivedTime] < '" + ((DateTime)time).ToString("yyyy-MM-dd HH:mm") + "'";
            var count = oFolder.Items.Restrict(restriction).Count;//Cast<object>().ToList();
            for (int i = 0; i < count; i++)
            {
                var crntReceivedTime = ((OutLook.MailItem)oFolder.Items.Restrict(restriction).Cast<object>().ToList()[i]).ReceivedTime;
                if (crntReceivedTime > time)
                {
                    string t = "";
                }
            }

Theoretically the line string t = ""; should never be called, because I determined the Items to never have entries which ReceivedTime's value is bigger than time. The problem is the line gets called, what means the restricted Items Collection contains entries which its shouldn't contain.

Did I do something wrong or is the Restrict()-method just failing?



Solution 1:[1]

Firstly, you are using multiple dot notation. You are calling Restrict (which is expensive even if it is called once) on each step of the loop. Call it once, cache the returned (restricted) Items collection, then loop over the items in that collection.

Secondly, what is the full restriction? You are using += to add an extra restriction on ReceivedTime. What is the actual value of the restriction variable?

Edit: I had no problem with the following script executed from OutlookSpy (I am its author - click Script button, paste the script, click Run):

restriction = " [ReceivedTime] < '2011-06-11 00:00' "
set Folder = Application.ActiveExplorer.CurrentFolder
set restrItems = Folder.Items.Restrict(restriction)
for each item in restrItems
  if TypeName(item) = "MailItem" Then
    Debug.Print item.ReceivedTime & " - " & item.Subject
  End If
next

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dmitry Streblechenko