搜索
首页后端开发C++为什么在 C# 中实现通用 OrderedDictionary?

Why Implement a Generic OrderedDictionary in C#?

实现通用的 OrderedDictionary 并不是特别困难,但它不必要地耗费时间,坦率地说,这个类是 Microsoft 的一个巨大疏忽。有多种方法可以实现此目的,但我选择使用 KeyedCollection 作为内部存储。我还选择实现各种方法来对 List 进行排序。确实如此,因为这本质上是 IList 和 IDictionary 的混合体。

这是界面。请注意,它包括 System.Collections.Specialized.IOrderedDictionary,这是 Microsoft 提供的此接口的非通用版本。

// https://choosealicense.com/licenses/unlicense
// 或 https://choosealicense.com/licenses/mit/
使用系统;
使用System.Collections.Generic;
using System.Collections.Specialized;

命名空间 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 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);
}
</tkey></keyvaluepair></tvalue></tvalue></tkey></tkey></tkey>

}
这是与帮助程序一起的实现类:

// http://unlicense.org
使用 System;
使用 System.Collections.ObjectModel;
使用 System.Diagnostics;
使用 System.Collections;
使用 System.Collections.Specialized;
使用 System.Collections.Generic;
使用System.Linq;

命名空间 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 tvalue>> _keyedCollection;

    /// <summary>
    /// Gets or sets the value associated with the specified key.
    /// </summary>
    /// <param name='"key"'>The key associated with the value to get or set.
    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='"index"'>The index of the value to get or set.
    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 tvalue>>(x => x.Key, comparer);
        }
        else {
            _keyedCollection = new KeyedCollection2<tkey keyvaluepair 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 = _keyedCollection.Count) {
            throw new ArgumentException(String.Format("The index was outside the bounds of the dictionary: {0}", index));
        }
        return _keyedCollection[index];
    }

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

    public IEnumerator<keyvaluepair tvalue>> GetEnumerator() {
        return _keyedCollection.GetEnumerator();
    }

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

    public void RemoveAt(int index</keyvaluepair></tkey></tkey></tvalue></tkey></tkey></tkey></tkey></tkey></tkey></tkey></tkey></tkey></tkey></tkey></tkey></tvalue></tkey></tkey></tkey></tkey>

以上是为什么在 C# 中实现通用 OrderedDictionary?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
C在现代世界中:应用和行业C在现代世界中:应用和行业Apr 23, 2025 am 12:10 AM

C 在现代世界中的应用广泛且重要。1)在游戏开发中,C 因其高性能和多态性被广泛使用,如UnrealEngine和Unity。2)在金融交易系统中,C 的低延迟和高吞吐量使其成为首选,适用于高频交易和实时数据分析。

C XML库:比较和对比选项C XML库:比较和对比选项Apr 22, 2025 am 12:05 AM

C 中有四种常用的XML库:TinyXML-2、PugiXML、Xerces-C 和RapidXML。1.TinyXML-2适合资源有限的环境,轻量但功能有限。2.PugiXML快速且支持XPath查询,适用于复杂XML结构。3.Xerces-C 功能强大,支持DOM和SAX解析,适用于复杂处理。4.RapidXML专注于性能,解析速度极快,但不支持XPath查询。

C和XML:探索关系和支持C和XML:探索关系和支持Apr 21, 2025 am 12:02 AM

C 通过第三方库(如TinyXML、Pugixml、Xerces-C )与XML交互。1)使用库解析XML文件,将其转换为C 可处理的数据结构。2)生成XML时,将C 数据结构转换为XML格式。3)在实际应用中,XML常用于配置文件和数据交换,提升开发效率。

C#vs. C:了解关键差异和相似之处C#vs. C:了解关键差异和相似之处Apr 20, 2025 am 12:03 AM

C#和C 的主要区别在于语法、性能和应用场景。1)C#语法更简洁,支持垃圾回收,适用于.NET框架开发。2)C 性能更高,需手动管理内存,常用于系统编程和游戏开发。

C#与C:历史,进化和未来前景C#与C:历史,进化和未来前景Apr 19, 2025 am 12:07 AM

C#和C 的历史与演变各有特色,未来前景也不同。1.C 由BjarneStroustrup在1983年发明,旨在将面向对象编程引入C语言,其演变历程包括多次标准化,如C 11引入auto关键字和lambda表达式,C 20引入概念和协程,未来将专注于性能和系统级编程。2.C#由微软在2000年发布,结合C 和Java的优点,其演变注重简洁性和生产力,如C#2.0引入泛型,C#5.0引入异步编程,未来将专注于开发者的生产力和云计算。

C#vs. C:学习曲线和开发人员的经验C#vs. C:学习曲线和开发人员的经验Apr 18, 2025 am 12:13 AM

C#和C 的学习曲线和开发者体验有显着差异。 1)C#的学习曲线较平缓,适合快速开发和企业级应用。 2)C 的学习曲线较陡峭,适用于高性能和低级控制的场景。

C#vs. C:面向对象的编程和功能C#vs. C:面向对象的编程和功能Apr 17, 2025 am 12:02 AM

C#和C 在面向对象编程(OOP)中的实现方式和特性上有显着差异。 1)C#的类定义和语法更为简洁,支持如LINQ等高级特性。 2)C 提供更细粒度的控制,适用于系统编程和高性能需求。两者各有优势,选择应基于具体应用场景。

从XML到C:数据转换和操纵从XML到C:数据转换和操纵Apr 16, 2025 am 12:08 AM

从XML转换到C 并进行数据操作可以通过以下步骤实现:1)使用tinyxml2库解析XML文件,2)将数据映射到C 的数据结构中,3)使用C 标准库如std::vector进行数据操作。通过这些步骤,可以高效地处理和操作从XML转换过来的数据。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。