欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现自定义Dictionary类实例

程序员文章站 2023-12-03 16:39:58
本文实例讲述了c#实现自定义dictionary类。分享给大家供大家参考。具体如下: 1.关于mydictionary类 本文中实现的mydictionary类具有如下...

本文实例讲述了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#程序设计有所帮助。