Learn some knowledge of collections. Collection: Generic collection, non-generic collection; Arraylist,hashtable,list<t>,dictionary<k,v> and so on, there are some common methods of collection.
One: Introduction to the collection
1: Features of the set
Generic collection using System.Collections.Generic
Non-generic collection using System.Collections
*: For arrays, the length is certain, may cause memory waste, but the collection can solve the problem, its length is dynamic change.
*: You can remove the data type limit for the array. The types within the collection can be different. In fact, the data stored in the collection is stored in the array, only the set of arrays are encapsulated.
* Collection gets the number of times with the count and array with length.
2: Classification of the collection
The following are common collections
Hashtable AA = new Hashtable (); Dictionary<int, int> aaa = new Dictionary<int, int> (); ArrayList arr = new ArrayList ();
* The set of key-value pairs ("hash table") contains a key and value to store the value. Each key corresponds to a unique value.
{Hashtable,dictionary<k,v>}
* ArrayList Collection
ArrayList ArrayList = new ArrayList (); Arraylist.add (ten); Pass the object type arraylist.add ("ten"); Here you can pass all the collection types, array types. Arraylist.addrange (arrayList); Arraylist.addrange (New int[]{1,4,5,5,5,5,5,}); Traversing elements through subscripts //inserting elements arraylist.insert (0, "Ahui"); Delete element < delete 7th element > arraylist.removeat (7); Console.WriteLine ("{0}", arraylist.capacity); Console.readkey ();
3: The collection cannot use traversal delete when deleting elements, because the total amount of each collection will be reduced. Call Clear () directly to delete the element.
4: Collection of common operations, add, Traverse, remove
Property
Capacity (number of items that can be accommodated in the collection, doubling growth)
Count (the number of actual stores in the collection)
Contains () contains an element
ToArray () collection conversions to arrays
5: For a collection, all of the other types will be saved as object types after they are loaded.
6: For a collection to sort by calling sort (), the default is in ascending order, and we can implement the IComparer interface inside it, sort by the objects we want to sort. Because the sort method is called, it will look for classes that implement the IComparer interface to sort.
* In the IComparer interface we want to implement its CompareTo method, which is compared in this area.
Class person:icomparable {public string Name {get; set;} public int Age {get; set;} public string Adress {get; set;} <summary> ////Implement IComparable interface, compare sort ///</summary> public int CompareTo (object obj) { var p = obj as person; Strongly convert object type to person type if (p!=null) { return p.age-this.age; } return 0; } }
7:hashtable Collection
*: This set is not the same as ArrayList, it is saved in the form of key,value format. (Key and Value), features: Key cannot be duplicated, is unique. You can only get values by key.
var hash=new Hashtable (); Hash. ADD ("1", "Ahui"); Hash. ADD ("2", new Indo () {name= "Zhang Hui"}); var dd = hash["2"] as Indo; Console.WriteLine (DD. Name); Console.readkey ();
Traversal of the *:hashtable collection
Because this collection does not have a Count property, you cannot use a for loop to traverse, at which point we can use foreach. < because it implements the IEnumerable interface >
*: There are three ways to find values
Traversal key foreach (var item in hash. Keys) { Console.WriteLine ("Key {0}--value {1}", Item,hash[item]); } Traverse the value foreach (var key in hash. Values) { Console.WriteLine (key); } Direct traversal of the key value pair foreach (DictionaryEntry kv in hash) { Console.WriteLine ("Key {0}, value {1}", KV. Key,kv. Value); } Console.readkey ();
8:list<> Collection
In the actual operation we seldom use the two previous sets [ArrayList and Hashtable], using generic collections [list<> and dictionary<k,v>], the function is that the previous collection can be added to various types, it is not very convenient to use, At this point, you have this generic collection, and you can only save specific types. And it expands a lot of ways.
9: String generator StringBuilder A variable sequence of characters
Var sb=new StringBuilder ();
The advantage of this string generator is that the length of the string is variable and varies with the length of the storage. Append a string to SB by append (): After you initialize a StringBuilder, it automatically applies a default StringBuilder capacity (the default is 16), which is controlled by capacity. And allow, we control the size of the capacity as needed, It is also possible to get or set the length of the StringBuilder by length;
Eg:stringbuilder variable string
var sb = new System.Text.StringBuilder (); Sb. Append ("123456789"); Add a string sb. Length =; Set the capacity to 3 Console.WriteLine (sb.) ToString ()); Output here: 123
Sb. Length = 30;//Reset Capacity to Console.WriteLine (sb.) ToString () + ", End");//Here is a space after the original string, to the length of the Console.WriteLine (sb. length);//The output here is 30
StringBuilder sb = new StringBuilder (); Sb. Append (1); Sb. Append (1); Console.WriteLine (sb.) capacity); Console.WriteLine (sb.) Length);
10:stringbuilder<> Collection
Var str=new stringbuilder<char,char>;
The type of this collection must be specified, and the value of the key inside it cannot be the same. The corresponding value can be found by the key, which holds the form of a two-dimensional array.
Two: Exercises
EG1: Calculates the number of occurrences of letters in a string, not case-sensitive.
String msg = "Welcome, to china! World! DSJFDSL.JFDSF "; msg = Msg. ToLower (); Dictionary<char, int> dict = new Dictionary<char, int> (); Declare a kv set, K save the specific value inside, v Save the number of occurrences. for (int i = 0; i < MSG. Length; i++) {if (char. Isletter (Msg[i]))//remove anything other than the letter {if (dict. ContainsKey (Msg[i])//dict inside there is this thing {dict[msg[i]]++; The MSG key is added, and the value inside is added 1} else {Dict[msg[i]] = 1; }}}//Output note type KeyValuePair foreach (Keyvaluepair<char, int> kv in Dict) {Console.WriteLine ("{0}{1}", Kv. Key, KV. Value); } console.readkey ();
EG2: Converts 123 to uppercase.
String str = "1q 2w 3e 4r 5t 6y 7u 8i 9o"; var dict = new Dictionary<char, char> (); string[] parts = str. Split ('); Spilt how to divide a string into a string array for (int i = 0; i < parts. Length; i++) { dict. ADD (Parts[i][0], parts[i][1]); Here the storage is a two-dimensional array } Console.WriteLine ("Please enter a number:??"). "); String number = Console.ReadLine (); StringBuilder sb = new StringBuilder (); A variable character sequence for (int i = 0; i < number. Length; i++) { sb. Append (Dict[number[i]); } Console.WriteLine (sb.) ToString ()); Console.readkey ();
EG3: Returns the odd number in an int array to a new int array
Int[] Arry = {1, 2, 3, 4, 5, 6, 7, 8, 9}; list<int> arr = new list<int> (); for (int i = 0; i < Arry. Length; i++) { if (Arry[i]% 2! = 0) { arr. ADD (Arry[i]); } } int[] AA = arr. ToArray (); for (int i = 0; i < AA. Length; i++) { Console.WriteLine (aa[i]); } Console.readkey ();
EG4: Randomly produces 10 digits, even numbers, not duplicates
ArrayList arr = new ArrayList (); Random random = new random (); Declares a random number var n = random. Nextdouble (); Console.WriteLine (n); while (arr. Count <) //The number within the collection cannot exceed { var num = random. Next (1, 101); if (num% 2 = = 0 &&!arr. Contains (num)) //Even, do not repeat { arr. ADD (num); } } Console.WriteLine ("Total is {0}", arr.) capacity); foreach (var item in arr) { Console.WriteLine (item); } Console.readkey ();
EG5: Insert Delete Duplicate
ArrayList arr1 = new ArrayList () {"A", "B", "C", "D", "E"}; ArrayList arr2 = new ArrayList () {"D", "E", "F", "G", "H"}; var arr3 = new ArrayList (new string[] {"11", "222", "1", "2"}); Arr1. Insertrange (0,ARR2); foreach (var item in arr1) {Console.WriteLine (item); } Console.WriteLine ("**************"); for (int i = 0; i < arr2. Count; i++) {if (!arr1. Contains (Arr2[i])) {arr1. ADD (Arr2[i]); }} Console.WriteLine (arr1. Count); foreach (var item in arr1) {Console.WriteLine (item); } console.readkey ();
Eg6: Randomly produces 10 digits, even numbers, not duplicates
ArrayList arr = new ArrayList (); Random random = new random (); Declares a random number var n = random. Nextdouble (); Console.WriteLine (n); while (arr. Count <) //The number within the collection cannot exceed { var num = random. Next (1, 101); if (num% 2 = = 0 &&!arr. Contains (num)) //Even, do not repeat { arr. ADD (num); } } Console.WriteLine ("Total is {0}", arr.) capacity); foreach (var item in arr) { Console.WriteLine (item); } Console.readkey ();
Eg7:list<> set and dictionary collection, modify the above set, even use the List<> collection to implement
list<int> even = new list<int> (); list<int> Oven = new list<int> (); String sb = "1 2 3 4 5 6 7 8 9"; string[] num = sb. Split ('); for (int i = 0; i < Num. Length; i++) { if (int. Parse (Num[i])% 2 = = 0)) { oven.add (int). Parse (Num[i])); } else { even.add (int). Parse (Num[i])); } } Even.addrange (Oven); foreach (var item in even) { Console.WriteLine (item); } Console.readkey ();
C # Fundamentals 03