'Converting Collection of Bookmarks to List<Bookmark>

I get the bookmarks in an existing Word-Document as follows

using System.Collections.Generic;
using Word = Microsoft.Office.Interop.Word;

namespace Word_Project
{
  public class WordDoc
  {
    public Word.Application App { get; set; }
    public Word.Document Document { get; set; }
    public Word.Bookmarks Bookmarks { get; set; }

    public WordDoc(string pathToDoc)
    {
        App = new Word.Application();
        Document = App.Documents.Open(pathToDoc);

        Bookmarks = Document.Bookmarks;
    }
  }
}

the Signature of Bookmarks is

public interface Bookmarks : System.Collections.IEnumerable

I'd like to convert this to a List<> (System.Collections.Generic) Bookmarks doesn't contain a .ToList()-Method and casting didn't work either.

(List<Bookmark>)Bookmarks //error

Maybe it isn't possible in the first place, as Bookmarks is an Interface, but if someone has a solution I would appreciate it.



Solution 1:[1]

I'm answering only from docs because I havent Office and so, can't use Interop. Seems that Microsoft.Office.Interop.Word.Bookmarks only exposes the GetEnumerator method, so you also cant go for a lambda foreach -> select aproach.

Well then I propose a very generic solution.

    private List<T> EnumeratorToList<T>(IEnumerator<T> em) 
    {
        List<T> listOut = new List<T>();
        while (em.MoveNext())
        {
            T val = em.Current;
            listOut.Add(val);
        }
        return listOut;
    }

Then call like:

List<Bookmark> myNewList = EnumeratorToList(Document.Bookmarks.GetEnumerator());

you can use yield return instead returning a list, but OP asked for a List

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 J.Salas