In this appendix we will make use of LINQ to access an Outlook object and get details of contacts.
Create a new .NET Console application using the File | New | Project | Windows | Console application option in Visual Studio. Add a reference to the Outlook Object Library to the project folder, as shown below.
The above image shows Microsoft Outlook 11.0 Object Library added to the project. This provides an interface to access Outlook properties, which will let us collect contact information from Outlook.
Add the following namespace to the project:
using Microsoft.Office.Interop.Outlook;
Now add the following code to the Main
method of the project:
_Application outlook = new Application(); // Contacts MAPIFolder folder = outlook.ActiveExplorer().Session .GetDefaultFolder(OlDefaultFolders.olFolderContacts); var contacts = from contact in folder.Items.OfType<ContactItem>() select contact; foreach (var contact in contacts) { Console.WriteLine(contact.FirstName); }
The above code references the Contacts folder. A LINQ query is used to access contact details from the folder by enumerating through the Items
of type ContactItem
.
Each item within the Contacts list has different properties that can be seen when we create a new contact in Outlook.
In the example we are collecting the FirstName of all the contacts in the contacts list. The output of the example would be:
LINQ queries can also be used to access addresses, tasks, mails, etc. The following code shows a query for collecting details from the address book.
// Addresses var addresses = from address in folder.Items.OfType<AddressList>() select address; foreach (var addres in addresses) { Console.WriteLine(addres.Name); }
LINQ queries are not only used for accessing XML, database and Outlook objects, but also to access information from Microsoft Excel, Microsoft Project, Microsoft Word and others.
18.191.237.176