Heim > Backend-Entwicklung > C++ > Warum ein generisches OrderedDictionary in C# implementieren?

Warum ein generisches OrderedDictionary in C# implementieren?

Linda Hamilton
Freigeben: 2025-01-01 00:45:09
Original
755 Leute haben es durchsucht

Why Implement a Generic OrderedDictionary in C#?

Ein generisches OrderedDictionary zu implementieren ist nicht besonders schwierig, aber es ist unnötig zeitaufwändig und ehrlich gesagt ist diese Klasse ein großes Versehen von Microsoft. Es gibt mehrere Möglichkeiten, dies zu implementieren, aber ich habe mich für die Verwendung einer KeyedCollection für meinen internen Speicher entschieden. Ich habe mich auch dafür entschieden, verschiedene Methoden zum Sortieren zu implementieren, damit List Dies ist der Fall, da es sich im Wesentlichen um eine Mischung aus IList und IDictionary handelt.

Hier ist die Schnittstelle. Beachten Sie, dass es System.Collections.Specialized.IOrderedDictionary enthält, die nicht generische Version dieser Schnittstelle, die von Microsoft bereitgestellt wurde.

// https://choosealicense.com/licenses/unlicense
// oder https://choosealicense.com/licenses/mit/
using System;
using System.Collections.Generic;
unter Verwendung von System.Collections.Specialized;

Namespace mattmc3.Common.Collections.Generic {

public interface IOrderedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IOrderedDictionary {
    new TValue this[int index] { get; set; }
    new TValue this[TKey key] { get; set; }
    new int Count { get; }
    new ICollection<TKey> Keys { get; }
    new ICollection<TValue> Values { get; }
    new void Add(TKey key, TValue value);
    new void Clear();
    void Insert(int index, TKey key, TValue value);
    int IndexOf(TKey key);
    bool ContainsValue(TValue value);
    bool ContainsValue(TValue value, IEqualityComparer<TValue> comparer);
    new bool ContainsKey(TKey key);
    new IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator();
    new bool Remove(TKey key);
    new void RemoveAt(int index);
    new bool TryGetValue(TKey key, out TValue value);
    TValue GetValue(TKey key);
    void SetValue(TKey key, TValue value);
    KeyValuePair<TKey, TValue> GetItem(int index);
    void SetItem(int index, TValue value);
}
Nach dem Login kopieren

}
Hier ist die Implementierung zusammen mit dem Hilfsprogramm Klassen:

// http://unlicense.org
using System;
mit System.Collections.ObjectModel;
mit System.Diagnostics;
mit System.Collections;
mit System.Collections.Specialized;
mit System.Collections.Generic;
Verwenden des System.Linq;

Namespace mattmc3.Common.Collections.Generic {

/// <summary>
/// A dictionary object that allows rapid hash lookups using keys, but also
/// maintains the key insertion order so that values can be retrieved by
/// key index.
/// </summary>
public class OrderedDictionary<TKey, TValue> : IOrderedDictionary<TKey, TValue> {

    #region Fields/Properties

    private KeyedCollection2<TKey, KeyValuePair<TKey, TValue>> _keyedCollection;

    /// <summary>
    /// Gets or sets the value associated with the specified key.
    /// </summary>
    /// <param name=&quot;key&quot;>The key associated with the value to get or set.</param>
    public TValue this[TKey key] {
        get {
            return GetValue(key);
        }
        set {
            SetValue(key, value);
        }
    }

    /// <summary>
    /// Gets or sets the value at the specified index.
    /// </summary>
    /// <param name=&quot;index&quot;>The index of the value to get or set.</param>
    public TValue this[int index] {
        get {
            return GetItem(index).Value;
        }
        set {
            SetItem(index, value);
        }
    }

    public int Count {
        get { return _keyedCollection.Count; }
    }

    public ICollection<TKey> Keys {
        get {
            return _keyedCollection.Select(x => x.Key).ToList();
        }
    }

    public ICollection<TValue> Values {
        get {
            return _keyedCollection.Select(x => x.Value).ToList();
        }
    }

    public IEqualityComparer<TKey> Comparer {
        get;
        private set;
    }

    #endregion

    #region Constructors

    public OrderedDictionary() {
        Initialize();
    }

    public OrderedDictionary(IEqualityComparer<TKey> comparer) {
        Initialize(comparer);
    }

    public OrderedDictionary(IOrderedDictionary<TKey, TValue> dictionary) {
        Initialize();
        foreach (KeyValuePair<TKey, TValue> pair in dictionary) {
            _keyedCollection.Add(pair);
        }
    }

    public OrderedDictionary(IOrderedDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) {
        Initialize(comparer);
        foreach (KeyValuePair<TKey, TValue> pair in dictionary) {
            _keyedCollection.Add(pair);
        }
    }

    #endregion

    #region Methods

    private void Initialize(IEqualityComparer<TKey> comparer = null) {
        this.Comparer = comparer;
        if (comparer != null) {
            _keyedCollection = new KeyedCollection2<TKey, KeyValuePair<TKey, TValue>>(x => x.Key, comparer);
        }
        else {
            _keyedCollection = new KeyedCollection2<TKey, KeyValuePair<TKey, TValue>>(x => x.Key);
        }
    }

    public void Add(TKey key, TValue value) {
        _keyedCollection.Add(new KeyValuePair<TKey, TValue>(key, value));
    }

    public void Clear() {
        _keyedCollection.Clear();
    }

    public void Insert(int index, TKey key, TValue value) {
        _keyedCollection.Insert(index, new KeyValuePair<TKey, TValue>(key, value));
    }

    public int IndexOf(TKey key) {
        if (_keyedCollection.Contains(key)) {
            return _keyedCollection.IndexOf(_keyedCollection[key]);
        }
        else {
            return -1;
        }
    }

    public bool ContainsValue(TValue value) {
        return this.Values.Contains(value);
    }

    public bool ContainsValue(TValue value, IEqualityComparer<TValue> comparer) {
        return this.Values.Contains(value, comparer);
    }

    public bool ContainsKey(TKey key) {
        return _keyedCollection.Contains(key);
    }

    public KeyValuePair<TKey, TValue> GetItem(int index) {
        if (index < 0 || index >= _keyedCollection.Count) {
            throw new ArgumentException(String.Format(&quot;The index was outside the bounds of the dictionary: {0}&quot;, index));
        }
        return _keyedCollection[index];
    }

    /// <summary>
    /// Sets the value at the index specified.
    /// </summary>
    /// <param name=&quot;index&quot;>The index of the value desired</param>
    /// <param name=&quot;value&quot;>The value to set</param>
    /// <exception cref=&quot;ArgumentOutOfRangeException&quot;>
    /// Thrown when the index specified does not refer to a KeyValuePair in this object
    /// </exception>
    public void SetItem(int index, TValue value) {
        if (index < 0 || index >= _keyedCollection.Count) {
            throw new ArgumentException(&quot;The index is outside the bounds of the dictionary: {0}&quot;.FormatWith(index));
        }
        var kvp = new KeyValuePair<TKey, TValue>(_keyedCollection[index].Key, value);
        _keyedCollection[index] = kvp;
    }

    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
        return _keyedCollection.GetEnumerator();
    }

    public bool Remove(TKey key) {
        return _keyedCollection.Remove(key);
    }

    public void RemoveAt(int index
Nach dem Login kopieren

Das obige ist der detaillierte Inhalt vonWarum ein generisches OrderedDictionary in C# implementieren?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage