How to get IDictionaryEnumerator from a generic IDictionary?

I have a dictionary as follows:

  IDictionary<string, string> dict;

How to create an enumerator that implements IDictionaryEnumerator (preferably using linq)?

+3
source share
4 answers

There must be something missing here, and that:

IDictionary obsoleteDict = dict as IDictionary;
if (obsoleteDict == null)
{
 //Do something here...
}
else
{
 return obsoleteDict.GetEnumerator();
}

(edit: yep, you should give it to the old non-common interface)

edit2: see Paul's comment below. A type implementation IDictionary<K,V>may or may not implement IDictionary ( Dictionary<K,V>although some implementations, such as WCF MessageProperties, do not work), so the cast may not work.

+3
source

IDictionaryEnumerator ; IEnumerator<KeyValuePair<string,string>>...

, ; :

using System;
using System.Collections;
using System.Collections.Generic;
static class Program
{
    class MyEnumerator<TKey,TValue> : IDictionaryEnumerator, IDisposable
    {
        readonly IEnumerator<KeyValuePair<TKey, TValue>> impl;
        public void Dispose() { impl.Dispose(); }
        public MyEnumerator(IDictionary<TKey, TValue> value)
        {
            this.impl = value.GetEnumerator();
        }
        public void Reset() { impl.Reset(); }
        public bool MoveNext() { return impl.MoveNext(); }
        public DictionaryEntry Entry { get { var pair = impl.Current;
            return new DictionaryEntry(pair.Key, pair.Value);} }
        public object Key { get { return impl.Current.Key; } }
        public object Value { get { return impl.Current.Value; } }
        public object Current {get {return Entry;}}
    }
    static IDictionaryEnumerator GetBasicEnumerator<TKey,TValue>(
        this IDictionary<TKey, TValue> data)
    {
        return new MyEnumerator<TKey, TValue>(data);
    }
    static void Main()
    {
        IDictionary<int, string> data = new Dictionary<int, string>()
        {
            {1,"abc"}, {2,"def"}
        };
        IDictionaryEnumerator basic;
        using ((basic = data.GetBasicEnumerator()) as IDisposable)
        {
            while (basic.MoveNext())
            {
                Console.WriteLine(basic.Key + "=" + basic.Value);
            }
        }
    }
}
+3

, IDictionaryEnumerator . IEnumerator.

KeyValuePair, IDictionaryEnumerator . , , IEnumerator<KeyValuePair<K,V>>.

+2

. , , .

return (IDictionaryEnumerator)dict.GetEnumerator();

, BCL , IDictionaryEnumerator ( , ):

  • Hashtable ( API).
  • Dictionary<T,K> ( API).
  • SortedList<T,K> ( API, )
+1

Source: https://habr.com/ru/post/1721208/


All Articles