Collection is flexible and contains many convenient classes.
For example, store data in hashTable.
Example: Hashtable ht = new Hashtable ();
Ht. Add ("white", "1Val ");
Ht. Add ("Xiao", "2Val ");
Ht. Add ("zhe", "3Val ");
Foreach (DictionaryEntry entry in ht)
{
Console. WriteLine (entry. Key + "->" + entry. Value );
}
========================================================== ==========================================
Set
(I). Set Type
1. General set
I. Array
A. The rank in Array is the dimension in Array. An Array can have one or more rank.
Array has a fixed capacity. If there is a variable capacity, use Array. CreateInstance, which can be stored from scratch.
II. ArrayList set type
A. is the complex version of the array. array is fixed, and the ArrayList class is automatically extended as needed. if Array. the value of the Capacity attribute is automatically re-allocated in memory and copied to the element.
B. ArrayList provides a method to Add/Remove a range of elements. In the Array, only one element value can be obtained or set at a time.
C. The synchronized method can be used to easily create a synchronization version of The arraylist. array will keep it until the user achieves synchronization.
D. arraylist provides a method to return read-only and fixed-size packages to the set. array does not.
E. array provides some flexibility not available in arraylist.
I. You can set the lower limit of array, but the lower limit of arraylist is always zero.
Ii. array can have multiple dimensions, while arraylist is always unique.
Iii. array is a specific type (not an object), which has better performance than arraylist. arraylist often involves unpacking and packing during storage and retrieval.
Iii. Hash table set
A. The hashtable class is based on the idictionary interface. Therefore, each element in the set is a key-value pair.
B. The object. gethashcode method generates hash code for itself. You can also use the hashtable constructor to specify a hash function for all elements.
Iv. sortedlist set type
A. The sortedlist class is similar to the combination of hashtable and arraylist.
B. Each element of sortedlist is a key-to-value pair. The method of returning only the key list or only the return value list is provided.
C. If you want a set of keys and values to be retained and the flexibility of indexes is required, use sortlist.
V. Queue set type
A. if you want to access the information in the same order as the information stored in the collection, use queue.
B. enqueue adds an element to the end of the queue. dequeue removes the oldest element from the queue. Peek returns the oldest element from the beginning of the queue, but does not remove it from the queue.
Vi. stack collection type
A. if you want to access the information in reverse order of information stored in the collection, use queue.
B. Push inserts an element at the top of the stack. Pop removes an element at the top of the stack. Peek returns the element at the top of the stack, but does not remove it from the top of the stack.
2. Bit Set
I. bitarray
A. bitarray is a collection class with the same capacity as the Count. Add the element to the bitarray by adding the Length attribute, and delete the element by reducing the Length attribute.
B. unique methods, such as AND/OR/XOR/not/setall.
C. In system. Collections.
Ii. bitvector32
A. fast, accurate 32-bit storage, and flags and small integers are stored at the same time.
B. It is located in system. Collections. Specialized.
3. Dedicated set
I. namevaluecollection
A. Based on nameobjectcollectionbase, but namevaluecollection can accept multiple values for each key, while nameobjectcollectionbase accepts each key, but only one value.
(2). Select which set to use
* ** Queue or stack: A Sequence List is required, and the elements in the list are discarded after retrieval. Otherwise, other sets are used.
* ** Queue or stack: access these elements in a certain order (first-in-first-out, and later-in-first-out). If they are random, use other sets.
* ** Do you want to access each element through indexes?
* Arraylist and stringcollection provide access to the element through the * Index * of the element starting from scratch.
* (Hashtable) (SortedList) (ListDictionary) (StringDictionary) provides access to its elements through the * Key * of the element
* (NameObjectCollectionBase) and (NameValueCollection) provide or access to the element through the * Index * of the element starting from scratch or through the * Key * of the element.
* ** Will each element contain a combination of one value, one value, and one key, or a combination of one key and multiple values?
* A value: Any set based on IList is used.
* One key and one value: Use any set based on IDictionary.
* One key and multiple values: Use the NameValueCollection class in the System. Collections. Specialized namespace.
* ** Do I need to sort elements in a different way than the element method?
* Hashtable sorts elements using the hash code of the key.
* SortedList is implemented based on IComparer and elements are sorted by keys.
* ArrayList provides the Sort method. This method uses IComparer implementation as a parameter.
* ** Do I need quick search and retrieval of information?
* For a small set (ten or fewer items), ListDictionary is faster than Hashtable.
* ** Do I need to accept only the set of strings?
* StringCollection (based on IList) and StringDictionary (based on IDictionary) are located in the System. Collections. Specialized namespace.
========================================================== ==========================================
Sort by SortedList
Using System;
Using System. Collections;
Comparison and sorting of namespace Sets
{
Public class Efficience: IComparable
{
Private int workHour;
Private int outPut;
Int IComparable. CompareTo (Object obj)
{
If (obj = null)
Throw new ArgumentException ("comparison object cannot be blank ");
If (! Obj. GetType (). Equals (this. GetType ()))
Throw new ArgumentException ("different types of comparison ");
Efficience objEffic = (Efficience) obj;
If (this. Effic> objEffic. Effic)
Return 1;
If (this. Effic <objEffic. Effic)
Return-1;
Return 0;
}
Public int WorkHour
{
Set
{
If (value <0)
Throw new ArgumentException ("the working time cannot be {0} or a negative number ");
WorkHour = value;
}
}
Public int OutPut
{
Set
{
If (value <0)
Throw new ArgumentException ("work output cannot be negative ");
OutPut = value;
}
}
Public float Effic
{
Get
{
Return (float) outPut/(float) workHour;
}
}
}
Class Class1
{
[STAThread]
Static void Main (string [] args)
{
Random rand = new Random ();
Efficience [] effics = new Efficience [5];
String [] persons = {"Xiaohua", "Diana", "Yanyan", "zhulin", "Lixin "};
Console. writeline ("generated effics array ");
// Console. writeline ("effics. getlowerbound (0) = {0}, effics. getupperbound (0) = {1} ", effics. getlowerbound (0), effics. getupperbound (0 ));
For (INT I = effics. getlowerbound (0); I <= effics. getupperbound (0); I ++)
{
Effics = new efficience ();
Effics. workhour = Rand. Next () % 24;
Effics. Output = Rand. Next () %1000;
Console. writeline ("person = {0}, effic = {1}", persons, effics. effic );
}
Sortedlist = new sortedlist ();
For (INT I = effics. getlowerbound (0); I <= effics. getupperbound (0); I ++)
{
Sortedlist. Add (effics, persons );
}
Console. writeline ("read content from sortedlist ");
Foreach (efficience effic in sortedlist. getkeylist ())
{
Console. WriteLine ("Person = {0}, Effic = {1}", sortedList [effic], effic. Effic );
}
Console. Read ();
}
}
}
========================================================== ==========================================
Copy of a set
Using System;
Using System. Collections;
Using System. Collections. Specialized;
Copying a namespace set
{
/// <Summary>
/// Summary of Class1.
/// </Summary>
Class Class1
{
[STAThread]
Static void Main (string [] args)
{
NameValueCollection namedVColl = new NameValueCollection ();
NamedVColl. Add ("Xiaohua", "13510532686 ");
NamedVColl. Add ("Xiaohua", "62658888 ");
NamedVColl. Add ("Xiao Yang", "1361030486 ");
NamedVColl. Add ("Xiao Yang", "62293218 ");
Foreach (string key in namedVColl. Keys)
Console. WriteLine ("name = {0}, phone = {1}", key, namedVColl [key]);
Console. WriteLine ("the set of named values obtained after copying ");
String [] arr = new string [namedVColl. Count];
NamedVColl. CopyTo (arr, 0 );
For (int I = arr. GetLowerBound (0); I <arr. GetUpperBound (0); I ++)
{
Console. WriteLine ("name = {0}, phone = {1}", namedVColl. AllKeys, arr );
}
Hashtable hhtable = new Hashtable ();
Hhtable ["Xiaohua"] = "Beijing ";
Hhtable ["Xiao Yang"] = "Nanjing ";
Console. WriteLine ("clone hash table ");
Foreach (object key in hhtable. Keys)
Console. WriteLine ("name = {0}, address = {1}", key, hhtable [key]);
Hashtable hhCloned = (Hashtable) hhtable. Clone ();
Hhtable ["Xiaohua"] = "Shanghai ";
Console. writeline ("clone and modify the initialization hash table ");
Foreach (Object key in hhtable. Keys)
Console. writeline ("name = {0}, address = {1}", key, hhtable [Key]);
Console. writeline ("clone Kazakh Greek table after hash table initialization after modification ");
Foreach (Object key in hhcloned. Keys)
{
Console. writeline ("name = {0}, address = {1}", key, hhcloned [Key]);
}
Console. Read ();
}
}
}
========================================================== ==========================================
Synchronous execution of Collections
Using system;
Using system. collections;
Using system. Collections. Specialized;
Namespace set and Synchronization
{
/// <Summary>
/// Summary of class1.
/// </Summary>
Class class1
{
Public static void DemoLockCollection ()
{
StringDictionary sDic = new StringDictionary ();
If (! SDic. IsSynchronized)
{
SDic. Add ("Xiaohua", "Garden Road ");
SDic ["Xiao Yang"] = "xinxingqiao ";
Foreach (string key in sDic. Keys)
Console. WriteLine ("name = {0}, address = {1}", key, sDic [key]);
}
Else
{
// Do not use synchronous processing code
}
}
[STAThread]
Static void Main (string [] args)
{
// The following code is used to run the class DemoLockCollection ().
Class1.DemoLockCollection ();
// The following code is another HashTable routine.
// Create and initialize a hash table
Hashtable myHT = new Hashtable ();
MyHT. Add (0, "zero ");
MyHT. Add (1, "one ");
MyHT. Add (2, "two ");
MyHT. Add (3, "three ");
MyHT. Add (4, "four ");
// Create thread-Safe Packaging
Hashtable mySyncdHT = Hashtable. Synchronized (myHT );
// Display the synchronization status of the Kazakh Greek table
Console. WriteLine ("myHT {0}.", myHT. IsSynchronized? "Synchronized": "No synchronization ");
Console. WriteLine ("mySncdHT {0}.", mySyncdHT. IsSynchronized? "Synchronized": "No synchronization ");
// Traverse the hash
Foreach (Object key in mySyncdHT. Keys)
Console. WriteLine ("Key = {0}, Value = {1]", key, mySyncdHT [key]);
Console. Read ();
}
}
}
========================================================== ==========================================
Array sorting (forward/backward)
Using System;
Namespace Array Operation
{
/// <Summary>
/// Summary of Class1.
/// </Summary>
Class Class1
{
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[Stathread]
Static void main (string [] ARGs)
{
//
// Todo: Add code here to start the application
//
String [] Friends = new string [] {"2 mojian", "1 zhengjian", "3 xugang", "4 guoyonghui "};
Console. writeline ("array data before operation :");
Foreach (string index in Friends)
{
Console. Write (index + "");
}
Array. Sort (Friends );
Console. writeline ("/n sorted data :");
For (INT I = friends. getlowerbound (0); I <= friends. getupperbound (0); I ++)
{
Console. Write (Friends + "");
}
Array. Reverse (Friends );
Console. writeline ("/n data in reverse order :");
For (int I = friends. GetLowerBound (0); I <= friends. GetUpperBound (0); I ++)
{
Console. Write (friends + "");
}
Console. WriteLine ();
Console. Read ();
}
}
}
========================================================== ==========================================
Custom comparator derived from IComparer
(1). Description
1. inherit from the IComparer interface and customize the comparator
2. Because the Array. Sort () method accepts the IComparer parameter, it performs a custom sorting rule.
In this example, IComparer is used as a parameter of the Sort method, and Icomparer is applied to the Array. Sort () method.
(2). Sample Code
Using System;
Using System. Collections;
Namespace comparator IComparer
{
/// <Summary>
/// Summary of Class1.
/// </Summary>
Public class Person
{
Public int ID;
Public int age;
Public Person ()
{
Id = 0;
Age = 0;
}
Public Person (int id, int age)
{
Id = ID;
Age = age;
}
Public void show ()
{
Console. writeline ("age = {0}, code = {1}", age, ID );
}
Public static void showpersons (person [] persons)
{
Foreach (person in persons)
Console. writeline ("age = {0}, code = {1}", person. Age, person. ID );
}
}
Public class personcomparer: system. Collections. icomparer
{
INT system. Collections. icomparer. Compare (Object X, object y)
{
If (x = NULL | Y = NULL)
Throw new ArgumentException ("the parameter cannot be blank ");
Person temp = new Person ();
If (! X. GetType (). Equals (temp. GetType () |! Y. GetType (). Equals (temp. GetType ()))
Throw new ArgumentException ("inconsistent types ");
Temp = null;
Person personX = (Person) x;
Person personY = (Person) y;
If (personX. ID> personY. ID)
Return 1;
If (personX. ID <personY. ID)
Return-1;
If (personX. Age> personY. Age)
Return 1;
If (personX. Age <personY. Age)
Return-1;
Return 0;
}
}
Class Class1
{
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[STAThread]
Static void Main (string [] args)
{
//
// TODO: Add code here to start the application
//
Random rand = new Random ();
Person [] persons = new Person [6];
Console. WriteLine ("the randomly generated Person array is :");
For (int I = 0; I <persons. GetLength (0); I ++)
{
Persons = new Person ();
Persons. ID = rand. Next () % 10;
Persons. Age = rand. Next () % 50;
Persons. Show ();
}
PersonComparer personComparer = new PersonComparer ();
// System. Collections. IComparer personComparer = new IComparer;
Array. Sort (persons, personComparer );
Console. WriteLine ("sorted Result :");
Person. ShowPersons (persons );
Person personToBeFind = new Person ();
Console. WriteLine ("Enter ID ");
PersonToBeFind. ID = int. Parse (Console. ReadLine ());
Console. WriteLine ("Enter Age ");
PersonToBeFind. Age = int. Parse (Console. ReadLine ());
Int index = Array. BinarySearch (persons, personToBeFind, personComparer );
If (index> = 0)
Console. WriteLine ("the element to be searched is the {0} element of the array", index + 1 );
Else
Console. WriteLine ("sorry, no element found ");
Console. ReadLine ();
}
}
}
//////////////////////////////////////// /////////////////////////////////////
Hashtable ilist
Public IList covertToIlist (Hashtable ht)
{
Ht. Add (1, "aaaa ");
Ht. Add (2, "bbbb ");
ArrayList arr = new ArrayList ();
Foreach (DictionaryEntry entry in ht)
{
Arr. Add (entry. Value );
}
Return arr;
}