C # Traversal in two ways for and foreach
For: You need to specify the first data, the end data, the data length, the value of the data can be changed in the FOR traversal statement, the traversal rules can be customized, the flexibility is higher
foreach: The IEnumerator interface needs to be implemented; The value of the data cannot be changed in the traversal; the traversal rule is only ' + + '; But the query is more efficient
Dictionary traversal mode:
dictionary<string,int> list =Newdictionary<string,int>(); list. ADD ("D",1);//3.0 or laterforeach(varIteminchlist) {Console.WriteLine (item. Key+item. Value);}//keyvaluepair<t,k>foreach(keyvaluepair<string,int> KVinchlist) {Console.WriteLine (kv. Key+KV. Value);}//by the collection of keysforeach(stringKeyinchlist. Keys) {Console.WriteLine (Key+List[key]);}//Direct Valueforeach(intValinchlist. Values) {Console.WriteLine (val);}//It is also possible to use the For methodlist<string> test =Newlist<string>(list. Keys); for(inti =0; I < list. Count; i++) {Console.WriteLine (Test[i]+List[test[i]]);}
List sort:
Hashtable ht=NewHashtable (); Ht. ADD ("E","e"); Ht. ADD ("A","a"); Ht. ADD ("C","C"); Ht. ADD ("B","b"); ArrayList LST=NewArrayList (HT. Keys); Lst. Sort (); foreach(stringKeyinchlst) {LISTBOX1.ITEMS.ADD ("Key:"+ key +"Vlaue:"+Ht[key]); }
Dictionary sort
Sorting ideas:
1> to save dictionary data with a list
2> to sort the new list
3> get sorted values from list, add them back into dictionary
protecteddictionary<string,int> Sortdictionary_desc (dictionary<string,int>dic) {List<KeyValuePair<string,int>> myList =Newlist<keyvaluepair<string,int>>(DIC); Mylist.sort (Delegate(keyvaluepair<string,int> S1, keyvaluepair<string,int>S2) { returnS2.Value.CompareTo (S1. Value); }); Dic. Clear (); foreach(keyvaluepair<string,int> PairinchmyList) {dic. ADD (pair. Key, pair. Value); } returndic; } protecteddictionary<string,int> Sortdictionary_asc (dictionary<string,int>dic) {List<KeyValuePair<string,int>> myList =Newlist<keyvaluepair<string,int>>(DIC); Mylist.sort (Delegate(keyvaluepair<string,int> S1, keyvaluepair<string,int>S2) { returns1.Value.CompareTo (S2. Value); }); Dic. Clear (); foreach(keyvaluepair<string,int> PairinchmyList) {dic. ADD (pair. Key, pair. Value); } returndic; }
The traversal and sequencing of C # dictionary