在做一个项目的过程中,需要将一些数据组织起来,第一个想到的就是HashTable,
主要就是考虑它用得比较广,再然后是KEY的唯一性,于是乎就用了。用了之后就发现了后果很严重:数据加入哈希表的时候的顺序和迭代输出的顺序不一致,这问题可真严重了,既然哈希表不能满足要求,只能用其它的数据结构了,找了一下就NameValueCollection了,用起来来还真好,主是没有支持KEY的唯一性,不可无所谓了,反正我这个项目也不好要求其唯一性了。 关于HashTable和NameValueCollection输出顺序对比可通过以下示例得出。using System;using System.Collections.Generic;using System.Collections;using System.Collections.Specialized;public class MyClass
{ public static void Main() { System.Collections.Hashtable ht = new System.Collections.Hashtable (); ht.Add ( "DdpMDisplaySeq".Trim ( ) , "Display Sequence".Trim ( ) ); ht.Add ( "DdpMNameChi".Trim ( ) , "Name (Chinese)".Trim ( ) ); ht.Add ( "DdpMNameEng".Trim ( ) , "Name (English)".Trim ( ) ); ht.Add ( "Comment".Trim ( ) , "Comment".Trim ( ) ); ht.Add ( "DdpMMarketCode".Trim ( ) , "Market Code".Trim ( ) ); foreach ( object key in ht.Keys ) { Console.WriteLine( "{0} {1} {2},{3}" , key , ht[key] , key.GetHashCode() , ht[key].GetHashCode() ); } NameValueCollection myCol = new NameValueCollection(); myCol.Add ( "DdpMDisplaySeq".Trim ( ) , "Display Sequence".Trim ( ) ); myCol.Add ( "DdpMNameChi".Trim ( ) , "Name (Chinese)".Trim ( ) ); myCol.Add ( "DdpMNameEng".Trim ( ) , "Name (English)".Trim ( ) ); myCol.Add ( "Comment".Trim ( ) , "Comment".Trim ( ) ); myCol.Add ( "DdpMMarketCode".Trim ( ) , "Market Code".Trim ( ) ); foreach ( string key in myCol.Keys ) { Console.WriteLine( "{0}/{1}" , key , myCol[key] ); }RL();
} Helper methods#region Helper methodsprivate static void WL(object text, params object[] args)
{ Console.WriteLine(text.ToString(), args); } private static void RL() { Console.ReadLine(); } private static void Break() { System.Diagnostics.Debugger.Break(); }#endregion
}输出结果为:DdpMDisplaySeq Display Sequence -1989459343,1288318213DdpMMarketCode Market Code 1652325269,-2031292722DdpMNameChi Name (Chinese) -408135670,-703205071DdpMNameEng Name (English) -1570541874,-1899340382Comment Comment -498702589,-498702589DdpMDisplaySeq/Display SequenceDdpMNameChi/Name (Chinese)DdpMNameEng/Name (English)Comment/CommentDdpMMarketCode/Market Code 2.NameValueCollection与Hashtable的区别a.引用区别hashtable:using System.Collections;
NameValueCollection:using System.Collections.Specialized;
b.键是否重复
NameValueCollection:允许重复.
HashTable是键-值集合,但键不能出现重复.
NameValueCollection myCol = new NameValueCollection(); myCol.Add("red", "rojo");//如果键值red相同结果合并 rojo,rouge myCol.Add("green", "verde"); myCol.Add("blue", "azul"); myCol.Add("red", "rouge");