C#集合之Hashtable

Hashtable是一个键值对集合,其泛型版本是Dictionary<K, V>,下面说下常用的一些方法;

1.Add(),向Hashtable添加元素,需要注意的是因为它是键值对集合,所以要同时添加一个键和一个值,且键不能重复。

2.ContainsKey(key)方法,是查询是否包含某个键,其Contains()方法最终也是调用这个方法实现的。

3.ContainsValue(value)方法,是查询是否包含某个值。

4.hash[“key”],根据键获取某个值。hash[“key”]=“修改”,根据键修改对应的值。

5.Remove(“key”);根据键删除对应的值。

需要注意的是,以上3个方法,其泛型版本Dictionary<K, V>也是一样的。

Keys属性,是Hashtable的键集合。Values属性,是Hashtable的值集合;可以通过foreach遍历它的键集合和值集合。

如果要同时得到Hashtable中的键集合和值集合,在使用foreach遍历时,请将var关键字替换为DictionaryEntry,这样就能同时拿到键和值了。

而对于Dictionary<K, V>要同时得到键集合和值集合,在使用foreach遍历时,请将var关键字替换为KeyValuePair<k,v>。

键值对集合,如果得到键,可以使用 集合名[键名]这样的索引方式获取对应的值。因为键值对集合不提供下标来访问,故这类集合不能通过for循环来遍历。

下面看几个例子程序,以便更好理解其实际应用:

1.将int数组中的奇数放到一个新的int数组中返回

int[] iArray = new int[] { 2, 7, 8, 3, 22, 9, 5, 11, 14, 18, 21 };
            ArrayList aLst = new ArrayList();
            for (int i = 0; i < iArray.Length; i++)
            {
                if (iArray[i] % 2 != 0)
                {
                    aLst.Add(iArray[i]);
                }
            }
            object[] obj = aLst.ToArray();
            foreach (var item in obj)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();

2.从一个整数的List<int>中取出最大数(找最大值)(最简单是调用List集合的max方法)

 1 private static int GetMax(List<int> iList)
 2         {
 3             int iMax = iList[0];
 4             for (int i = 0; i < iList.Count; i++)
 5             {
 6                 if (iList[i]>iMax)
 7                 {
 8                     iMax = iList[i];
 9                 }
10             }
11             return iMax;
12         }

3.把123转换为:壹贰叁。

 1 /// <summary>
 2         /// 数字转换成大写汉字
 3         /// </summary>
 4         /// <param name="msg"></param>
 5         /// <returns></returns>
 6         private static string ConvertInt(string msg)
 7         {
 8             string s = "0零 1壹 2贰 3叁 4肆 5伍 6陆 7柒 8扒 9玖";
 9             Dictionary<char, char> dic = new Dictionary<char, char>();
10
11             string[] strArray = s.Split(‘ ‘);
12             for (int i = 0; i < strArray.Length; i++)
13             {
14                 dic.Add(strArray[i][0], strArray[i][1]);
15             }
16
17             StringBuilder sb = new StringBuilder();
18
19             for (int i = 0; i < msg.Length; i++)
20             {
21                 if (dic.ContainsKey(msg[i]))
22                 {
23                     sb.Append(dic[msg[i]]);
24                 }
25                 else
26                 {
27                     sb.Append(msg[i]);
28                 }
29             }
30             return sb.ToString();
31         }

4.计算字符串中每种字母出现的次数(面试题)。 “Welcome ,to Chinaworld”

 1             Dictionary<char, int> dic = new Dictionary<char, int>();
 2
 3             for (int i = 0; i < msg.Length; i++)
 4             {
 5                 if (!dic.ContainsKey(msg[i]))
 6                 {
 7                     dic.Add(msg[i], 1);
 8                 }
 9                 else
10                 {
11                     dic[msg[i]] = dic[msg[i]] + 1;
12                 }
13             }
14
15             foreach (KeyValuePair<char, int> item in dic)
16             {
17                 Console.WriteLine("字符<{0}>在文本中出现了{1}次", item.Key, item.Value);
18             }

延伸,如果是要统计一段中文中,某个词组呢?

 1 string msg = "患者:“大夫,我咳嗽得很重。”     大夫:“你多大年记?”     患者:“七十五岁。”     大夫:“二十岁咳嗽吗”患者:“不咳嗽。”     大夫:“四十岁时咳嗽吗?”     患者:“也不咳嗽。”     大夫:“那现在不咳嗽,还要等到什么时咳嗽?”";
 2             string key = "咳嗽";
 3             int iIndex = msg.IndexOf(key, 0);
 4             if (iIndex!=-1)
 5             {
 6                 Console.WriteLine("字符{0}第1次出现的位置是:{1}", key, iIndex);
 7             }
 8
 9             int iCount = 1;
10             while (iIndex != -1)
11             {
12                 iIndex = msg.IndexOf(key, iIndex + key.Length);
13                 if (iIndex != -1)
14                 {
15                     iCount++;
16                     Console.WriteLine("字符{0}第{1}次出现的位置是:{2}", key, iCount, iIndex);
17                 }
18                 else
19                 {
20                     break;
21                 }
22             }

5.编写一个函数进行日期转换,将输入的中文日期转换为阿拉伯数字日期,比如:二零一二年十二月月二十一日要转换为2012-12-21

 1 private static string ConvertDate(string strDate)
 2         {
 3             Dictionary<char, char> dic = new Dictionary<char, char>();
 4             string s = "零0 一1 二2 三3 四4 五5 六6 七7 八8 九9";
 5             string[] strArray = s.Split(‘ ‘);
 6             for (int i = 0; i < strArray.Length; i++)
 7             {
 8                 dic.Add(strArray[i][0], strArray[i][1]);
 9             }
10
11             StringBuilder sb = new StringBuilder();
12             for (int j = 0; j < strDate.Length; j++)
13             {
14                 if (dic.ContainsKey(strDate[j]))
15                 {
16                     sb.Append(dic[strDate[j]]);
17                 }
18                 else
19                 {
20                     if (strDate[j]==‘十‘)
21                     {
22                         //1.十  10    10
23                         //2.二十 20   0
24                         //3.十二 12   1
25                         //4.二十二 22   不翻译
26
27                         if (!dic.ContainsKey(strDate[j - 1]) && !dic.ContainsKey(strDate[j + 1]))
28                         {
29                             sb.Append("10");
30                         }
31                         else if (dic.ContainsKey(strDate[j - 1]) && !dic.ContainsKey(strDate[j + 1]))
32                         {
33                             sb.Append("0");
34                         }
35                         else if (!dic.ContainsKey(strDate[j - 1]) && dic.ContainsKey(strDate[j + 1]))
36                         {
37                             sb.Append("1");
38                         }
39                         else if (dic.ContainsKey(strDate[j - 1]) && dic.ContainsKey(strDate[j + 1]))
40                         {
41
42                         }
43                     }
44                     else
45                     {
46                         sb.Append(strDate[j]);
47                     }
48                 }
49             }
50             string n = sb.ToString().Replace(‘年‘,‘-‘);
51             n = n.Replace(‘月‘, ‘-‘);
52             return n.Replace(‘日‘,‘ ‘);
53         }

上面代码中的中文注释还对不同情况做了判断。

关于集合,先就说这么多,写出来算是给自己的总结,留作他日复习用。如果各路大神有补充,请跟我联系,共同进步啊!

C#集合之Hashtable

时间: 2024-08-05 10:04:48

C#集合之Hashtable的相关文章

C#集合类型——Hashtable、Dictionary之浅谈

Hashtable表 数组.数组集合.List集合都是通过索引来访问里面成员.哈希表则是通过键来访问成员值.键不可为空,值可为空. 比如: Hashtable  hash=new  Hashtable(); hash.Add("one","chen"); hash.Add("two","li"); Console.WriteLine(hash["one"]); 运行结果:chen 基本的常用方法 1,添加

15-07-10 Stack集合、queue集合、hashtable集合

1.栈:Stack,先进后出,一个一个赋值,一个一个取值,按顺序. .count           取集合内元素的个数 .push()         将元素一个一个推入集合中//stack集合存入用.push() .pop()           将元素一个个弹出集合 .clear()         清空集合 Stack s = new Stack();//先存入的后取出 s.Push(1); s.Push(2); s.Push(3); Console.WriteLine(s.Pop())

集合之HashTable

在java中与有两个类都提供了一个多种用途的hashTable机制,他们都可以将可以key和value结合起来构成键值对通过put(key,value)方法保存起来,然后通过get(key)方法获取相对应的value值.一个是前面提到的HashMap,还有一个就是马上要讲解的HashTable.对于HashTable而言,它在很大程度上和HashMap的实现差不多,如果我们对HashMap比较了解的话,对HashTable的认知会提高很大的帮助.他们两者之间只存在几点的不同,这个后面会阐述. 一

从内部剖析C#集合之HashTable

计划写几篇文章专门介绍HashTable,Dictionary,HashSet,SortedList,List 等集合对象,从内部剖析原理,以便在实际应用中有针对性的选择使用. 这篇文章先介绍HashTable . 先例举几个问题:1,Hashtable为什么速度查询速度快,而添加速度相对慢,且其添加和查询速度之比相差一个数量等级? 2,装填因子( Load Factor)是什么,hashtable默认的装填因子是多少? 3,hashtable里的元素是顺序排序的吗? 4,hashtable内部

双列集合之hashtable

一.hashtable和ArrayList的性能比较 hashtable比ArrayList取值更快.原因是前者是根据键直接取值,但是ArrayList是循环整个集合,找到需要的元素. 二.hashtable的用法 1 static void Main(string[] args) 2 { 3 Hashtable hs = new Hashtable(); 4 hs.Add("zs","张三"); 5 hs.Add("ls", "李四&

Stack集合、queue集合、hashtable集合

1.栈:Stack,先进后出,一个一个赋值,一个一个取值,按顺序. .count           取集合内元素的个数 .push()         将元素一个一个推入集合中//stack集合存入用.push() .pop()           将元素一个个弹出集合 .clear()         清空集合 Stack s = new Stack();//先存入的后取出 s.Push(1); s.Push(2); s.Push(3); Console.WriteLine(s.Pop())

Map集合、HashMap集合、LinkedHashMap集合、Hashtable集合、Collections工具类和模拟斗地主洗牌和发牌

1.Map集合概述和特点 * A:Map接口概述  * 查看API可以知道:  * 将键映射到值的对象  * 一个映射不能包含重复的键  * 每个键最多只能映射到一个值 * B:Map接口和Collection接口的不同  * Map是双列的,Collection是单列的  * Map的键唯一,Collection的子体系Set是唯一的  * Map集合的数据结构值针对键有效,跟值无关;Collection集合的数据结构是针对元素有效 2.Map集合的功能概述 * A:Map集合的功能概述  *

ava集合(四)Set集合之HashTable详解

概要 前一章,我们学习了HashMap.这一章,我们对Hashtable进行学习.我们先对Hashtable有个整体认识,然后再学习它的源码,最后再通过实例来学会使用Hashtable.第1部分 Hashtable介绍第2部分 Hashtable数据结构第3部分 Hashtable源码解析(基于JDK1.6.0_45)第4部分 Hashtable遍历方式第5部分 Hashtable示例 转载请注明出处:http://www.cnblogs.com/skywang12345/p/3310887.h

Java集合之Hashtable源码分析

概述 Hashtable也是基于哈希表实现的, 与map相似, 不过Hashtable是线程安全的, Hashtable不允许 key或value为null. 成员变量 Hashtable的数据结构和HashMap一样, 采用 数组加链表的方式实现. 几个成员变量与HashMap一样: 方法 Hashtable的方法与HashMap基本一样, 只是 Hashtable方法加上了 synchronized 关键字, 保证Hashtable是线程安全的. 主要说说Hashtable与HashMap的