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

为什么在 C# 中实现通用 OrderedDictionary?

Jan 01, 2025 am 12:45 AM

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<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);
}
登录后复制

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

// 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<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
登录后复制

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

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热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

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

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

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

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

C语言数据结构:树和图的数据表示与操作 C语言数据结构:树和图的数据表示与操作 Apr 04, 2025 am 11:18 AM

C语言数据结构:树和图的数据表示与操作树是一个层次结构的数据结构由节点组成,每个节点包含一个数据元素和指向其子节点的指针二叉树是一种特殊类型的树,其中每个节点最多有两个子节点数据表示structTreeNode{intdata;structTreeNode*left;structTreeNode*right;};操作创建树遍历树(先序、中序、后序)搜索树插入节点删除节点图是一个集合的数据结构,其中的元素是顶点,它们通过边连接在一起边可以是带权或无权的数据表示邻

C语言文件操作难题的幕后真相 C语言文件操作难题的幕后真相 Apr 04, 2025 am 11:24 AM

文件操作难题的真相:文件打开失败:权限不足、路径错误、文件被占用。数据写入失败:缓冲区已满、文件不可写、磁盘空间不足。其他常见问题:文件遍历缓慢、文本文件编码不正确、二进制文件读取错误。

c语言函数的基本要求有哪些 c语言函数的基本要求有哪些 Apr 03, 2025 pm 10:06 PM

C语言函数是代码模块化和程序搭建的基础。它们由声明(函数头)和定义(函数体)组成。C语言默认使用值传递参数,但也可使用地址传递修改外部变量。函数可以有返回值或无返回值,返回值类型必须与声明一致。函数命名应清晰易懂,使用驼峰或下划线命名法。遵循单一职责原则,保持函数简洁性,以提高可维护性和可读性。

c语言函数名定义 c语言函数名定义 Apr 03, 2025 pm 10:03 PM

C语言函数名定义包括:返回值类型、函数名、参数列表和函数体。函数名应清晰、简洁、统一风格,避免与关键字冲突。函数名具有作用域,可在声明后使用。函数指针允许将函数作为参数传递或赋值。常见错误包括命名冲突、参数类型不匹配和未声明的函数。性能优化重点在函数设计和实现上,而清晰、易读的代码至关重要。

c上标3下标5怎么算 c上标3下标5算法教程 c上标3下标5怎么算 c上标3下标5算法教程 Apr 03, 2025 pm 10:33 PM

C35 的计算本质上是组合数学,代表从 5 个元素中选择 3 个的组合数,其计算公式为 C53 = 5! / (3! * 2!),可通过循环避免直接计算阶乘以提高效率和避免溢出。另外,理解组合的本质和掌握高效的计算方法对于解决概率统计、密码学、算法设计等领域的许多问题至关重要。

c语言函数的概念 c语言函数的概念 Apr 03, 2025 pm 10:09 PM

C语言函数是可重复利用的代码块,它接收输入,执行操作,返回结果,可将代码模块化提高可复用性,降低复杂度。函数内部机制包含参数传递、函数执行、返回值,整个过程涉及优化如函数内联。编写好的函数遵循单一职责原则、参数数量少、命名规范、错误处理。指针与函数结合能实现更强大的功能,如修改外部变量值。函数指针将函数作为参数传递或存储地址,用于实现动态调用函数。理解函数特性和技巧是编写高效、可维护、易理解的C语言程序的关键。

CS-第 3 周 CS-第 3 周 Apr 04, 2025 am 06:06 AM

算法是解决问题的指令集,其执行速度和内存占用各不相同。编程中,许多算法都基于数据搜索和排序。本文将介绍几种数据检索和排序算法。线性搜索假设有一个数组[20,500,10,5,100,1,50],需要查找数字50。线性搜索算法会逐个检查数组中的每个元素,直到找到目标值或遍历完整个数组。算法流程图如下:线性搜索的伪代码如下:检查每个元素:如果找到目标值:返回true返回falseC语言实现:#include#includeintmain(void){i

C语言多线程编程:新手指南与疑难解答 C语言多线程编程:新手指南与疑难解答 Apr 04, 2025 am 10:15 AM

C语言多线程编程指南:创建线程:使用pthread_create()函数,指定线程ID、属性和线程函数。线程同步:通过互斥锁、信号量和条件变量防止数据竞争。实战案例:使用多线程计算斐波那契数,将任务分配给多个线程并同步结果。疑难解答:解决程序崩溃、线程停止响应和性能瓶颈等问题。

See all articles