Export (0) Print
Expand All

IDictionaryEnumerator Interface

Enumerates the elements of a nongeneric dictionary.

Namespace:  System.Collections
Assembly:  mscorlib (in mscorlib.dll)

[ComVisibleAttribute(true)]
public interface class IDictionaryEnumerator : IEnumerator

The IDictionaryEnumerator type exposes the following members.

  NameDescription
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsCurrentGets the current element in the collection. (Inherited from IEnumerator.)
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEntryGets both the key and the value of the current dictionary entry.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsKeyGets the key of the current dictionary entry.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsValueGets the value of the current dictionary entry.
Top

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMoveNextAdvances the enumerator to the next element of the collection. (Inherited from IEnumerator.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsResetSets the enumerator to its initial position, which is before the first element in the collection. (Inherited from IEnumerator.)
Top

[Visual Basic, C#]

The foreach statement of the C# language (for each in Visual Basic) hides the complexity of the enumerators. Therefore, using foreach is recommended instead of directly manipulating the enumerator.

Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.

Initially, the enumerator is positioned before the first element in the collection. The Reset method also brings the enumerator back to this position. At this position, calling the Current property throws an exception. Therefore, you must call the MoveNext method to advance the enumerator to the first element of the collection before reading the value of Current.

Current returns the same object until either MoveNext or Reset is called. MoveNext sets Current to the next element.

If MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext returns false. When the enumerator is at this position, subsequent calls to MoveNext also return false. If the last call to MoveNext returned false, calling Current throws an exception. To set Current to the first element of the collection again, you can call Reset followed by MoveNext.

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and the next call to MoveNext or Reset throws an InvalidOperationException. If the collection is modified between MoveNext and Current, Current returns the element that it is set to, even if the enumerator is already invalidated.

The enumerator does not have exclusive access to the collection; therefore, enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

Notes to Implementers

The Current property that is inherited from IEnumerator returns an Object that is a boxed DictionaryEntry, similar to the return value of the Entry property.

This code example shows how to define a dictionary enumerator that implements the IDictionaryEnumerator interface.

using namespace System;
using namespace System::Collections;

// This class implements a simple dictionary using an array of 
// DictionaryEntry objects (key/value pairs). 
public ref class SimpleDictionary : public IDictionary
{
    // The array of items 
private:
    array<DictionaryEntry^>^ items;
private:
    int itemsInUse;

    // Construct the SimpleDictionary with the desired number of 
    // items. The number of items cannot change for the life time of 
    // this SimpleDictionary. 
public:
    SimpleDictionary(int size)
    {
        items = gcnew array<DictionaryEntry^>(size);
    }

    #pragma region IDictionary Members
public:
    property virtual bool IsReadOnly
    {
        bool get()
        {
            return false;
        }
    }
public:
    virtual bool Contains(Object^ key)
    {
        int index;
        return TryGetIndexOfKey(key, &index);
    }
public:
    virtual property bool IsFixedSize
    {
        bool get()
        {
            return false;
        }
    }
public:
    virtual void Remove(Object^ key)
    {
        if (key == nullptr)
        {
            throw gcnew ArgumentNullException("key");
        }
        // Try to find the key in the DictionaryEntry array 
        int index;
        if (TryGetIndexOfKey(key, &index))
        {
            // If the key is found, slide all the items down.
            Array::Copy(items, index + 1, items, index, itemsInUse -
                index - 1);
            itemsInUse--;
        }
        else
        {
            // If the key is not in the dictionary, just return. 
            return;
        }
    }
public:
    virtual void Clear()
    {
        itemsInUse = 0;
    }
public:
    virtual void Add(Object^ key, Object^ value)
    {
        // Add the new key/value pair even if this key already exists 
        // in the dictionary. 
        if (itemsInUse == items->Length)
        {
            throw gcnew InvalidOperationException
                ("The dictionary cannot hold any more items.");
        }
        items[itemsInUse++] = gcnew DictionaryEntry(key, value);
    }
public:
    virtual property ICollection^ Keys
    {
        ICollection^ get()
        {
            // Return an array where each item is a key. 
            array<Object^>^ keys = gcnew array<Object^>(itemsInUse);
            for (int i = 0; i < itemsInUse; i++)
            {
                keys[i] = items[i]->Key;
            }
            return keys;
        }
    }
public:
    virtual property ICollection^ Values
    {
        ICollection^ get()
        {
            // Return an array where each item is a value. 
            array<Object^>^ values = gcnew array<Object^>(itemsInUse);
            for (int i = 0; i < itemsInUse; i++)
            {
                values[i] = items[i]->Value;
            }
            return values;
        }
    }
public:
    virtual property Object^ default[Object^]
    {
        Object^ get(Object^ key)
        {
            // If this key is in the dictionary, return its value. 
            int index;
            if (TryGetIndexOfKey(key, &index))
            {
                // The key was found; return its value. 
                return items[index]->Value;
            }
            else
            {
                // The key was not found; return null. 
                return nullptr;
            }
        }

        void set(Object^ key, Object^ value)
        {
            // If this key is in the dictionary, change its value. 
            int index;
            if (TryGetIndexOfKey(key, &index))
            {
                // The key was found; change its value.
                items[index]->Value = value;
            }
            else
            {
                // This key is not in the dictionary; add this 
                // key/value pair.
                Add(key, value);
            }
        }
    }
private:
    bool TryGetIndexOfKey(Object^ key, int* index)
    {
        for (*index = 0; *index < itemsInUse; *index++)
        {
            // If the key is found, return true (the index is also 
            // returned). 
            if (items[*index]->Key->Equals(key))
            {
                return true;
            }
        }

        // Key not found, return false (index should be ignored by 
        // the caller). 
        return false;
    }
private:
    ref class SimpleDictionaryEnumerator : public IDictionaryEnumerator
    {
        // A copy of the SimpleDictionary object's key/value pairs. 
private:
        array<DictionaryEntry^>^ items;
private:
        int index;

public:
        SimpleDictionaryEnumerator(SimpleDictionary^ sd)
        {
            // Make a copy of the dictionary entries currently in the 
            // SimpleDictionary object.
            items = gcnew array<DictionaryEntry^>(sd->Count);
            Array::Copy(sd->items, 0, items, 0, sd->Count);
            index = -1;
        }

        // Return the current item. 
public:
        virtual property Object^ Current
        {
            Object^ get()
            {
                ValidateIndex();
                return items[index];
            }
        }

        // Return the current dictionary entry. 
public:
        virtual property DictionaryEntry Entry
        {
            DictionaryEntry get()
            {
                return (DictionaryEntry) Current;
            }
        }

        // Return the key of the current item. 
public:
        virtual property Object^ Key
        {
            Object^ get()
            {
                ValidateIndex();
				return items[index]->Key;
            }
        }

        // Return the value of the current item. 
public:
        virtual property Object^ Value
        {
            Object^ get()
            {
                ValidateIndex();
                return items[index]->Value;
            }
        }

        // Advance to the next item. 
public:
        virtual bool MoveNext()
        {
            if (index < items->Length - 1)
            {
                index++;
                return true;
            }
            return false;
        }

        // Validate the enumeration index and throw an exception if 
        // the index is out of range. 
private:
        void ValidateIndex()
        {
            if (index < 0 || index >= items->Length)
            {
                throw gcnew InvalidOperationException
                    ("Enumerator is before or after the collection.");
            }
        }

        // Reset the index to restart the enumeration. 
public:
        virtual void Reset()
        {
            index = -1;
        }
    };
public:
    virtual IDictionaryEnumerator^ GetEnumerator()
    {
        // Construct and return an enumerator. 
        return gcnew SimpleDictionaryEnumerator(this);
    }
    #pragma endregion

    #pragma region ICollection Members
public:
    virtual property bool IsSynchronized
    {
        bool get()
        {
            return false;
        }
    }

public:
    virtual property Object^ SyncRoot
    {
        Object^ get()
        {
            throw gcnew NotImplementedException();
        }
    }

public:
    virtual property int Count
    {
        int get()
        {
            return itemsInUse;
        }
    }

public:
    virtual void CopyTo(Array^ array, int index)
    {
        throw gcnew NotImplementedException();
    }
    #pragma endregion

    #pragma region IEnumerable Members

    virtual IEnumerator^ IEnumerable_GetEnumerator() 
        = IEnumerable::GetEnumerator
    {
        // Construct and return an enumerator. 
        return ((IDictionary^)this)->GetEnumerator();
    }
    #pragma endregion
};

int main()
{
    // Create a dictionary that contains no more than three 
    // entries.
    IDictionary^ d = gcnew SimpleDictionary(3);

    // Add three people and their ages to the dictionary.
    d->Add("Jeff", 40);
    d->Add("Kristin", 34);
    d->Add("Aidan", 1);

    Console::WriteLine("Number of elements in dictionary = {0}",
        d->Count);

    Console::WriteLine("Does dictionary contain 'Jeff'? {0}",
        d->Contains("Jeff"));
    Console::WriteLine("Jeff's age is {0}", d["Jeff"]);

    // Display every entry's key and value. 
    for each (DictionaryEntry^ de in d)
    {
        Console::WriteLine("{0} is {1} years old.", de->Key,
            de->Value);
    }

    // Remove an entry that exists.
    d->Remove("Jeff");

    // Remove an entry that does not exist, but do not throw an 
    // exception.
    d->Remove("Max");

    // Show the names (keys) of the people in the dictionary. 
    for each (String^ s in d->Keys)
    {
        Console::WriteLine(s);
    }

    // Show the ages (values) of the people in the dictionary. 
    for each (int age in d->Values)
    {
        Console::WriteLine(age);
    }
}

// This code produces the following output. 
// 
// Number of elements in dictionary = 3 
// Does dictionary contain 'Jeff'? True 
// Jeff's age is 40 
// Jeff is 40 years old. 
// Kristin is 34 years old. 
// Aidan is 1 years old. 
// Kristin 
// Aidan 
// 34 
// 1

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft