搜索
首页后端开发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 Destructors vs垃圾收集器:有什么区别?C Destructors vs垃圾收集器:有什么区别?May 13, 2025 pm 03:25 PM

C DestructorSprovidePreciseControloverResourCemangement,whergarBageCollectorSautomateMoryManagementbutintroduceunPredicational.c Destructors:1)允许CustomCleanUpactionsWhenObextionsWhenObextSaredSaredEstRoyed,2)RorreasereSouresResiorSouresiorSourseResiorMeymemsmedwhenEbegtsGoOutofScop

C和XML:在项目中集成数据C和XML:在项目中集成数据May 10, 2025 am 12:18 AM

在C 项目中集成XML可以通过以下步骤实现:1)使用pugixml或TinyXML库解析和生成XML文件,2)选择DOM或SAX方法进行解析,3)处理嵌套节点和多级属性,4)使用调试技巧和最佳实践优化性能。

在C中使用XML:库和工具指南在C中使用XML:库和工具指南May 09, 2025 am 12:16 AM

在C 中使用XML是因为它提供了结构化数据的便捷方式,尤其在配置文件、数据存储和网络通信中不可或缺。1)选择合适的库,如TinyXML、pugixml、RapidXML,根据项目需求决定。2)了解XML解析和生成的两种方式:DOM适合频繁访问和修改,SAX适用于大文件或流数据。3)优化性能时,TinyXML适合小文件,pugixml在内存和速度上表现好,RapidXML处理大文件优异。

C#和C:探索不同的范例C#和C:探索不同的范例May 08, 2025 am 12:06 AM

C#和C 的主要区别在于内存管理、多态性实现和性能优化。1)C#使用垃圾回收器自动管理内存,C 则需要手动管理。2)C#通过接口和虚方法实现多态性,C 使用虚函数和纯虚函数。3)C#的性能优化依赖于结构体和并行编程,C 则通过内联函数和多线程实现。

C XML解析:技术和最佳实践C XML解析:技术和最佳实践May 07, 2025 am 12:06 AM

C 中解析XML数据可以使用DOM和SAX方法。1)DOM解析将XML加载到内存,适合小文件,但可能占用大量内存。2)SAX解析基于事件驱动,适用于大文件,但无法随机访问。选择合适的方法并优化代码可提高效率。

c在特定领域:探索其据点c在特定领域:探索其据点May 06, 2025 am 12:08 AM

C 在游戏开发、嵌入式系统、金融交易和科学计算等领域中的应用广泛,原因在于其高性能和灵活性。1)在游戏开发中,C 用于高效图形渲染和实时计算。2)嵌入式系统中,C 的内存管理和硬件控制能力使其成为首选。3)金融交易领域,C 的高性能满足实时计算需求。4)科学计算中,C 的高效算法实现和数据处理能力得到充分体现。

揭穿神话:C真的是一种死语吗?揭穿神话:C真的是一种死语吗?May 05, 2025 am 12:11 AM

C 没有死,反而在许多关键领域蓬勃发展:1)游戏开发,2)系统编程,3)高性能计算,4)浏览器和网络应用,C 依然是主流选择,展现了其强大的生命力和应用场景。

C#vs. C:编程语言的比较分析C#vs. C:编程语言的比较分析May 04, 2025 am 12:03 AM

C#和C 的主要区别在于语法、内存管理和性能:1)C#语法现代,支持lambda和LINQ,C 保留C特性并支持模板。2)C#自动内存管理,C 需要手动管理。3)C 性能优于C#,但C#性能也在优化中。

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

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

热门文章

热工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

SecLists

SecLists

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

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器