C#自己实现的Dictionary类

1.关于MyDictionary类

本文中实现的MyDictionary类具有如下功能

1)可以增加、修改、删除键值对

2)可以通过索引器,找到一个键对应的值

3)可以遍历打印类中全部的键值对

4)可以将类中的序列转化为有序的(不排序、升序、降序)List类型

MyDictionary类是一个具有两个参数的泛型类,内部机制采用以键值对(KeyValuePair)类型为元素的双向链表(LinkedList)实现

2.实现代码

class MyDictioinary<TKey, TValue>
{
    LinkedList<KeyValuePair<TKey, TValue>> llDictionary
        = new LinkedList<KeyValuePair<TKey, TValue>>();

    /// <summary>
    /// 索引器,输入TKey可以找到对应的TValue
    /// </summary>
    /// <param name="tk">键值</param>
    /// <returns></returns>
    public TValue this[TKey tk]
    {
        get
        {
            foreach(KeyValuePair<TKey, TValue> kvp in llDictionary)
            {
                if (tk.Equals(kvp.Key))
                {
                    return kvp.Value;
                }
            }
            return default(TValue);
        }
    }

    /// <summary>
    /// 添加一组数据
    /// </summary>
    /// <param name="tk"></param>
    /// <param name="tv"></param>
    public void Add(TKey tk, TValue tv)
    {
        foreach (KeyValuePair<TKey, TValue> kvp in llDictionary)
        {
            if (tk.Equals(kvp.Key))
            {
                throw new Exception("新增失败:主键已经存在");
            }
        }
        llDictionary.AddLast(new KeyValuePair<TKey, TValue>(tk, tv));
    }

    /// <summary>
    /// 删除一组数据
    /// </summary>
    /// <param name="tk"></param>
    public void Delete(TKey tk)
    {
        foreach (KeyValuePair<TKey, TValue> kvp in llDictionary)
        {
            if (tk.Equals(kvp.Key))
            {
                llDictionary.Remove(kvp);
                return;
            } 
        }
        throw new Exception("删除失败:不存在这个主键");
    }

    /// <summary>
    /// 修改一组数据
    /// </summary>
    /// <param name="tk"></param>
    /// <param name="tv"></param>
    public void Modify(TKey tk, TValue tv)
    {
        LinkedListNode<KeyValuePair<TKey, TValue>> lln = llDictionary.First;
        while (lln != null )
        {
            if (tk.Equals(lln.Value.Key))
            {
                llDictionary.AddBefore(lln, new KeyValuePair<TKey, TValue>(tk, tv));
                llDictionary.Remove(lln);
                return;
            }
            lln = lln.Next;
        }
        throw new Exception("修改失败:不存在这个主键");
    }

    /// <summary>
    /// 打印整个Dictionary内的全部数据
    /// </summary>
    public void PrintData()
    {
        Console.WriteLine("==================");
        Console.WriteLine("输出数据");
        Console.WriteLine("==================");
        foreach (KeyValuePair<TKey, TValue> kvp in llDictionary)
        {
            Console.WriteLine(kvp.Key.ToString() + "\t:" + kvp.Value.ToString());
        }
        Console.WriteLine(string.Format("共计输出 {0} 项", llDictionary.Count));
        Console.WriteLine(DateTime.Now.ToLongTimeString());
        Console.WriteLine("==================");
    }

    /// <summary>
    /// 决定按什么顺序打印Dictionary内的数据
    /// </summary>
    public enum PrintType
    {
        Normal = 0, //不排序
        Ascend = 1, //升序排列
        Descend = 2 //降序佩列
    };

    /// <summary>
    /// 返回List类型的数据
    /// </summary>
    /// <param name="printType">List内数据的排序情况</param>
    /// <returns></returns>
    public List<KeyValuePair<TKey, TValue>> ToList(PrintType printType = PrintType.Normal)
    {
        switch (printType)
        {
            case PrintType.Normal:
                {
                    return llDictionary.ToList();
                }
            case PrintType.Ascend:
                {
                    if (llDictionary.Count == 0) return null;

                    LinkedList<KeyValuePair<TKey, TValue>> newll = 
                        new LinkedList<KeyValuePair<TKey, TValue>>();

                    try
                    {
                        LinkedListNode<KeyValuePair<TKey, TValue>> lln = llDictionary.First;
                        while (lln != null)
                        {
                            LinkedListNode<KeyValuePair<TKey, TValue>> lln2 = newll.First;
                            while (lln2 != null)
                            {
                                //Key是字符串的情况
                                if (llDictionary.First.Value.Key.GetType() == 
                                    "string".GetType())
                                {
                                    if (string.Compare(lln2.Value.Key.ToString(),
                                        lln.Value.Key.ToString()) > 0)
                                    {
                                        newll.AddBefore(lln2, new LinkedListNode
                                            <KeyValuePair<TKey, TValue>>(lln.Value));
                                        break;
                                    }
                                }
                                else //Key可以被转化为浮点数的情况
                                {
                                    if (double.Parse(lln2.Value.Key.ToString()) >
                                        double.Parse(lln.Value.Key.ToString()))
                                    {
                                        newll.AddBefore(lln2, new LinkedListNode
                                            <KeyValuePair<TKey, TValue>>(lln.Value));
                                        break;
                                    }
                                }

                                lln2 = lln2.Next;
                            }
                            if (lln2 == null)
                            {
                                newll.AddLast(new LinkedListNode
                                    <KeyValuePair<TKey, TValue>>(lln.Value));
                            }

                            lln = lln.Next;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

                    return newll.ToList();
                }
            case PrintType.Descend:
                {
                    if (llDictionary.Count == 0) return null;

                    LinkedList<KeyValuePair<TKey, TValue>> newll =
                        new LinkedList<KeyValuePair<TKey, TValue>>();

                    try
                    {
                        LinkedListNode<KeyValuePair<TKey, TValue>> lln = llDictionary.First;
                        while (lln != null)
                        {
                            LinkedListNode<KeyValuePair<TKey, TValue>> lln2 = newll.First;
                            while (lln2 != null)
                            {
                                //Key是字符串的情况
                                if (llDictionary.First.Value.Key.GetType() == 
                                    "string".GetType())
                                {
                                    if (string.Compare(lln2.Value.Key.ToString(),
                                        lln.Value.Key.ToString()) < 0)
                                    {
                                        newll.AddBefore(lln2, new LinkedListNode
                                            <KeyValuePair<TKey, TValue>>(lln.Value));
                                        break;
                                    }
                                }
                                else //Key可以被转化为浮点数的情况
                                {
                                    if (double.Parse(lln2.Value.Key.ToString()) <
                                        double.Parse(lln.Value.Key.ToString()))
                                    {
                                        newll.AddBefore(lln2, new LinkedListNode
                                            <KeyValuePair<TKey, TValue>>(lln.Value));
                                        break;
                                    }
                                }

                                lln2 = lln2.Next;
                            }
                            if (lln2 == null)
                            {
                                newll.AddLast(new LinkedListNode
                                    <KeyValuePair<TKey, TValue>>(lln.Value));
                            }

                            lln = lln.Next;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

                    return newll.ToList();
                }
            default: return null;
        }
    }
}

3.Main函数调用示例

static void Main(string[] args)
{
    MyDictioinary<string, string> dic = new MyDictioinary<string, string>();

    //插入两组数据
    dic.Add("1", "MERCURY");
    dic.Add("2", "VENUS");

    //尝试插入重复主键的数据 报警:主键不存在
    try
    {
        dic.Add("1", "EARTH");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

    //删除一组数据
    dic.Delete("1");
    //添加一组数据
    dic.Add("1", "MARS");
    //修改两组数据
    dic.Modify("1", "JUPITER");
    dic.Modify("2", "SATURN");
    //添加两组数据
    dic.Add("6", "SUN");
    dic.Add("5", "MOON");
    dic.Add("8", "URANUS");
    dic.Add("9", "NEPTUNE");

    dic.PrintData();

    //通过索引找到对应值
    Console.WriteLine("key为6的元素value为:" + dic["6"]);
    Console.WriteLine("key为3的元素value为:" + dic["3"]);

    List<KeyValuePair<string, string>> l;

    //输出升序排列好的List
    l = dic.ToList(MyDictioinary<string, string>.PrintType.Ascend);
    Console.WriteLine("升序排列后的List:");
    for (int i = 0; i < l.Count; i++)
    {
        Console.WriteLine(l[i].Key.ToString() + "\t:" + l[i].Value.ToString());
    }

    //输出降序排列好的List
    l = dic.ToList(MyDictioinary<string, string>.PrintType.Descend);
    Console.WriteLine("降排列后的List:");
    for (int i = 0; i < l.Count; i++)
    {
        Console.WriteLine(l[i].Key.ToString() + "\t:" + l[i].Value.ToString());
    }

    Console.ReadLine();
}

4.运行示例

C#自己实现的Dictionary类

你可能感兴趣的:(C#自己实现的Dictionary类)