C# Interop Outlook 联系人未遍历所有项目

C# Interop Outlook Contacts not iterating through all Items

我想删除所有具有 CustomerID 的 Outlook 联系人。所以我认为使用 Interop 获取所有联系人并遍历它们并检查它们是否具有我想要的 CustomerID 会很容易。

这就是我编码的内容:

var app = new Application();

var folderContacts = app
  .ActiveExplorer()
  .Session
  .GetDefaultFolder(OlDefaultFolders.olFolderContacts);

var searchFolder = folderContacts.Items;

foreach (ContactItem foundContact in searchFolder)
    if (foundContact.CustomerID == myCustomerIdAsString)
        foundContact.Delete();

这会获取所有联系人,但我的问题是,它不会遍历所有项目。看这张图:

你可以看到,它遍历了大约一半的项目。但是不知道为什么。

有人知道该怎么做吗?

正如 Yosh 在他的评论中所写,searchFolder 项目在迭代本身中发生了变化。因此,我将要删除的实体放在一个集合中,并在迭代后删除它们。 我想删除所有具有 CustomerID 的 Outlook 联系人。所以我认为使用 Interop 获取所有联系人并遍历它们并检查它们是否具有我想要的 CustomerID 会很容易。

这就是我编码的内容:

var app = new Application();

var contacts = new List<ContactItem>();

var folderContacts = app
  .ActiveExplorer()
  .Session
  .GetDefaultFolder(OlDefaultFolders.olFolderContacts);

var searchFolder = folderContacts.Items;

foreach (ContactItem foundContact in searchFolder)
    if (foundContact.CustomerID == myCustomerIdAsString)
        contacts.Add(foundContact);

contacts.ForEach(x => x.Delete());