当前位置:   article > 正文

C# 实现一个支持重复键值的字典_c#实现可以重复键值对的字典

c#实现可以重复键值对的字典
using System;
using System.Collections.Generic;

public class RepeatDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
{
    private readonly List<TKey> _keys = new List<TKey>();

    private readonly List<TValue> _values = new List<TValue>();


    public void Add(TKey key, TValue value)
    {
        _keys.Add(key);
        _values.Add(value);
    }


    IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
    {
        for (int i = 0; i < _keys.Count; i++)
        {
            yield return new KeyValuePair<TKey, TValue>(_keys[i], _values[i]);
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        for (int i = 0; i < _keys.Count; i++)
        {
            yield return new KeyValuePair<TKey, TValue>(_keys[i], _values[i]);
        }
    }
}

class Program
{
    static void Main()
    {
        RepeatDictionary<string, string> dictionary = new RepeatDictionary<string, string>()
        {
            {"aa","bb" },
            {"aa","cc" },
            {"aa","dd" },
        };

        foreach (var item in dictionary)
        {
            Console.WriteLine($"{item.Key},{item.Value}");
        }
        Console.ReadKey();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/969825
推荐阅读
相关标签
  

闽ICP备14008679号