How to: Use SetColumns to Efficiently Enumerate Items in a Folder

Office 2013 and later

This example shows how to improve the performance of enumerating the Items collection by using the SetColumns(String) method to cache certain properties of each item in the collection.

Programming Applications for Office Outlook 2007

The following code example is an excerpt from Programming Applications for Microsoft Office Outlook 2007, from Microsoft Press (ISBN 9780735622494, copyright Microsoft Press 2007, all rights reserved).

Buy this book

Sample chapters

To enumerate items in a collection, use the SetColumns method to cache properties on the Items collection. SetColumns takes an argument that is a comma-delimited string that represents property names. Once all items in the collection have been enumerated, call the ResetColumns() method to clear the property cache.

In the following code example, EnumerateContactsWithSetColumns uses the SetColumns method to cache the FileAs, CompanyName, and JobTitle properties of items in the Contacts folder. Note that you must test for empty strings or a null reference in the restriction.

Note that an Outlook folder can possibly contain items of different types. This code sample makes use of the OutlookItem helper class, defined in How to: Create a Helper Class to Access Common Outlook Item Members, to conveniently call the OutlookItem.Class property to verify the message class of each item in the filtered subset of items in the folder, before assuming the item is a contact item.

If you use Visual Studio to test this code example, you must first add a reference to the Microsoft Outlook 15.0 Object Library component and specify the Outlook variable when you import the Microsoft.Office.Interop.Outlook namespace. The using statement must not occur directly before the functions in the code example but must be added before the public Class declaration. The following line of code shows how to do the import and assignment in C#.

using Outlook = Microsoft.Office.Interop.Outlook;
private void EnumerateContactsWithSetColumns()
    // Obtain Contacts folder
    Outlook.Folder folder =
        as Outlook.Folder;
    string filter = "Not([CompanyName] Is Null)" +
        " AND Not([JobTitle] Is Null)";
    Outlook.Items items = folder.Items.Restrict(filter);
    items.SetColumns("FileAs, CompanyName, JobTitle");
    for (int i = 1; i <= items.Count; i++)
        // Create an instance of OutlookItem
        OutlookItem myItem = new OutlookItem(items[i]);
        if (myItem.Class == Outlook.OlObjectClass.olContact)
            // Use InnerObject to return ContactItem
            Outlook.ContactItem contact =
                myItem.InnerObject as Outlook.ContactItem;
            StringBuilder sb = new StringBuilder();

Other resources