Hashtable 注意:用foreach
注意:用foreach
下面是一个简单的例子:
class SampleHashtable
{ /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { // Create and initialize a new Hashtable. Hashtable table = new Hashtable(); //Student Name, Grade table.Add("leiwanjun", 100); table.Add("wanghuan", 87); table.Add("wuhailong", 92); table.Add("renyao", 76); table.Add("tanghonglei", 84); table.Add("chenxiaoping", 91); table.Add("liupeixun", 80); table.Add("huyoumou", 87);
// Display the properties and values of the Hashtable.
Console.WriteLine("Count: {0}", table.Count); PrintTable(table);
Console.WriteLine();
int g = (int) table["wuhailong"]; Console.WriteLine ("wuhailong's grade is: {0}", g);
Console.WriteLine();
PrintItems ("All Names", table.Keys); Console.WriteLine(); PrintItems ("All Grades", table.Values);
}
public static void PrintTable( Hashtable myList)
{ Console.WriteLine ("{0, -15} {1, -15}", "Name","Grade"); Console.WriteLine ("{0, -15} {1, -15}", "----","-----"); // // 排序 // ArrayList al = new ArrayList(myList.Keys); // al.Sort(); // foreach (string Name in al) // { // Console.WriteLine("{0, -15} {1, -15}", Name, myList[Name]); // } // // //遍历哈希表中的每个元素,直接输出 foreach (DictionaryEntry e in myList) { Console.WriteLine ("{0, -15} {1, -15}", e.Key, e.Value); } }
public static void PrintItems(string title, IEnumerable myList )
{ Console.Write ("{0}: ", title); StringBuilder sb = new StringBuilder(); foreach (object o in myList) { sb.AppendFormat( "{0}, ", o); } sb.Remove(sb.Length - 2, 2); Console.WriteLine(sb); |
转载于:https://www.cnblogs.com/hyfei0315/archive/2008/07/07/1237728.html