The c# collection analysis

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

What is a collection(collection)?

Provides a structured organization of arbitrary objects, from.NET's point of view, the so-called collection can be defined as an object, this object implements one or more of the System.Collections.ICollection, System.Collections.IDictionary and System.Collections.IList interface. The definition of the System.Collections namespace “ embedded ” set into three categories:

  * An ordered collection: just set the ICollection interface, under normal circumstances, the data item insertion sequence control with the object out of the order from the collection. System.Collections.Stack and System.Collections.Queue are typical examples of ICollection set.
* Index collection: a collection of Ilist, its content via the zero based number search out, like an array. The System.Collections.ArrayList object is an instance of the index set.
* Key type set: set the IDictionary interface, which contains the key value search can be certain types of projects. The contents of the IDictionary collection is usually the key value storage, can retrieve the enumeration sorting using way. The System.Collections.HashTable class implements the IDictionary interface.

OOP (object oriented programming) terms, the above interface this way to construct an object function, is polymorphism.

The System.Collections namespace contains interfaces and classes, these interfaces and classes that define the various objects (such as lists, queues, digit group, Hashi table and Dictionary) collection.
The System.Collections.Generic namespace contains the definition of a generic collection interfaces and classes, generic collection allows the user to create a strongly typed collections, type safety and performance, it can provide better than non generic strongly typed collections.
The System.Collections.Specialized namespace contains the collection, dedicated and strong type for example, linked list dictionary, bit vector and collections that contain only strings.

In the System.Collections namespace provides a number of interface:


SorryArrayList?

  A normal arrays and collections of mixed type (dynamic array, Array is the complex version)

Advantages: dynamic increase and decrease of elements

   Implementation of the ICollection and IList interface

   Sets the array flexible size

Disadvantages: ArrayList load greater than the traditional array and did not realize strict type, also can accept any conversion to the System.Object object, there are type safe and efficiency (interview point)

How to useArrayList

1 ArrayList al = new ArrayList(); 2 al.Add(100);//A single add 3 foreach (int number in new int[6] { 9, 3, 7, 2, 4, 8 }) 4 { 5 al.Add(number);//Collective add method 6 } 7 al.AddRange(new int[2] { 11, 12 });//The collective method of adding two 8 ArrayList al2 = new ArrayList(al.GetRange(1, 3));//The newArrayListJust take a part 9 foreach (int i in al)//Don't cast 10 { 11 Console.WriteLine(i); 12 } 13 for (int i = 0; i <al2.Count; i++)//The array islength 14 { 15 int number = (int)al2[i];//We must cast 16 Console.WriteLine(number); 17 } 18 IEnumerator ie=al.GetEnumerator(); 19 while(ie.MoveNext()) 20 { 21 Console.Write(ie.Curret.ToString()+" "); 22 } 23 Int32[] values = (Int32[])al.ToArray(typeof(Int32));//ReturnArrayListContains an array 24 View Code

ArrayListImportant methods and attributes

1 public ArrayList() 2 { 3 this._items = emptyArray; 4 } 5 public ArrayList(ICollection c) 6 { 7 if (c == null) 8 { 9 throw new ArgumentNullException("c", Environment.GetResourceString("ArgumentNull_Collection")); 10 } 11 int count = c.Count; 12 if (count == 0) 13 { 14 this._items = emptyArray; 15 } 16 else 17 { 18 this._items = new object[count]; 19 this.AddRange(c); 20 } 21 } 22 public ArrayList(int capacity) 23 { 24 if (capacity <0) 25 { 26 throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", new object[] { "capacity" })); 27 } 28 if (capacity == 0) 29 { 30 this._items = emptyArray; 31 } 32 else 33 { 34 this._items = new object[capacity]; 35 } 36 } public override int Add(object obj) 37 { 38 int num = this._list.Add(obj); 39 base._version++; 40 return num; 41 }

The IsSynchronized property, the ArrayList.Synchronized method
1- The IsSynchronized property indicates whether the current instance of ArrayList support thread synchronization 2- "and ArrayList.Synchronized static method will return a ArrayList thread synchronization package
1- If you use the example of non thread synchronization, when multiple threads that access, need to manually call lock to keep the synchronization of threads, for example:
ArrayList list = new ArrayList();
//...
lock( list.SyncRoot ) //When ArrayList is non thread package, the SyncRoot attribute is its own, but in order to meet the SyncRoot definition of ICollection, normative here or use SyncRoot to keep the source code
{
list.Add( “Add a Item” );
}
2- If the instance using the ArrayList.Synchronized method returns, so don't consider thread synchronization problem, the example itself is thread safe, in fact the internal ArrayList achieve a ensure thread synchronization inner class, ArrayList.Synchronized returns is an instance of this class, each attribute it is using the lock keyword to ensure thread synchronization.

However, the use of this method (ArrayList.Synchronized) does not guarantee the enumeration of the synchronization, for example, a thread is deleted or added collection item, and another thread at the same time of enumeration, the enumeration will throw an exception. So, in the enumeration of the time, you must explicitly use the SyncRoot lock this collection.

ArrayListAnd array conversion

1 ArrayList List = new ArrayList(); 2 List.Add(1); 3 List.Add(2); 4 List.Add(3); 5 Int32[] values = (Int32[])List.ToArray(typeof(Int32)); 6 7 ArrayList List = new ArrayList(); 8 List.Add(1); 9 List.Add(2); 10 List.Add(3); 11 Int32[] values = new Int32[List.Count]; 12 List.CopyTo(values); 13 14 15 //Add different types of elements to the array 16 ArrayList List = new ArrayList(); 17 List.Add( “string” ); 18 List.Add( 1 ); 19 object[] values = List.ToArray(typeof(object)); //Correct 20 string[] values = (string[])List.ToArray(typeof(string)); //Error

ArrayListThe best advice
    In this section we discuss the difference between ArrayList and array, and the efficiency of ArrayList
(1)ArrayList is a complex version of the Array, ArrayList encapsulate an array of type Object, from a general sense, it has no intrinsic difference and arrays, many methods and even to ArrayList, such as Index, IndexOf, Contains, Sort are corresponding to call the Array method directly based on the internal array.
(2)Internal Object type effects for general reference types, the influence is not very big, but for value types, into ArrayList to add and modify elements, will cause the package operation, frequent operation may affect a part of efficiency. To eliminate this influence is not, unless you don't use it, otherwise he has to pay a portion of the loss of efficiency, but this part of the loss will not be great.
(3)The array expansion, this is one of the factors that affect the efficiency of ArrayList is relatively large. Whenever Add implementation methods, AddRange, Insert, InsertRange and other elements are added, will check the inner array capacity is not enough, if it is, it will be two times the current capacity to construct an array element, the old Copy to the new array, then discard the old number group, the expansion operation in this critical point, should be more efficiency.
     Example 1: for example, one may have 200 elements of the dynamic data add to a default of 16 element size created ArrayList, will pass by:
  16*2*2*2*2 = the expansion will be 256 four times to meet the final demand, so if one begins with: ArrayList List = new ArrayList (210); the way to create ArrayList, will not only reduce the 4 array creation and operation of Copy, will reduce the memory usage.
(4)Call IndexOf, Contains and other methods of frequent (Sort, BinarySearch optimized method, not on the list) efficiency loss caused by
First of all, we must be clear, ArrayList is a dynamic array, it does not include the Key or Value for fast access algorithm, so it calls IndexOf, Contains method is the implementation of the simple cycle to find elements, so call such methods often than not you write cycle and some optimization to the quick, if any these requirements, recommend the use of Hashtable or SortedList a set of key value pairs.

Queue(Queue)AndStack(Stack):

  System.Collections.Stack and System.Collections.Queue, both only implements the ICollection interface, save System.Object type projects in accordance with the storage items to the assembly. According to the sequence of adding object can be retrieved from the set: the stack is a last in first out, while the queue is fifo. Normally, you can consider using these sets in the following situations:

* Receiving and processing in the collection order important project.
* You can discard it in processing project.
* You don't need to access to any item in the collection.

1 Queue 2 Queue qu = new Queue(); 3 Queue qu2 = new Queue(); 4 foreach (int i in new int[4] { 1, 2, 3, 4 }) 5 { 6 qu.Enqueue(i);//Enqueue 7 qu2.Enqueue(i); 8 } 9 10 foreach (int i in qu) 11 { 12 Console.WriteLine(i);//Traversal 13 } 14 15 qu.Dequeue();//The team 16 Console.WriteLine("Dequeue"); 17 foreach (int i in qu) 18 { 19 Console.WriteLine(i); 20 } 21 22 qu2.Peek();//Back in the Queue At the beginning of the object but does not remove it. 23 Console.WriteLine("Peek"); 24 foreach (int i in qu2) 25 { 26 Console.WriteLine(i); 27 } 28 29 Stack 30 Stack sk = new Stack(); 31 Stack sk2 = new Stack(); 32 foreach (int i in new int[4] { 1, 2, 3, 4 }) 33 { 34 sk.Push(i);//Stack 35 sk2.Push(i); 36 } 37 38 foreach (int i in sk) 39 { 40 Console.WriteLine(i);//Traversal 41 } 42 43 sk.Pop();//The stack 44 Console.WriteLine("Pop"); 45 foreach (int i in sk) 46 { 47 Console.WriteLine(i); 48 } 49 50 sk2.Peek();//The last item does not delete pop-up 51 Console.WriteLine("Peek"); 52 foreach (int i in sk2) 53 { 54 Console.WriteLine(i); 55 }

HashTable:

  The System.Collections.HashTable collection achieved IDictionary and Icollection, can be used to store various types of objects with string keys only association. Stored in order of the items in the HashTable collection in accordance with the Hashi code from its value is determined by the. Each object in the collection value must be unique, and the hash code is not necessarily the only.
What is the Hashi code? The Hashi code is essentially from a block of data to eliminate all redundant partial results, it is played on the data aided classification or ranking function. When a project is added to the collection, HashTable is calling key for GetHashCode method, because all the classes are inherited from System.Objec, so the call this method can determine the Hashi code and sort by this code storage. You can force the Hashi function using custom, method has two, one is GetHashCode method overloading class, two is passed to the HashTable constructor object that implements the System.Collections.IHashcodeProvider interface, in this case, the object will be used for all to join set key generated Hashi code.

From the perspective of performance, because the key search only with the same hash code value, so HashTable can quickly retrieve an arbitrary element from the set, thereby reducing the must pass the check to find the number of matching values. However, because the inserted into each object in the collection - key generated Hashi code corresponding to the must, so the project into the price is a little high. Therefore, HashTable is mainly used in accordance with any key repeatedly to retrieve large amounts of relatively static data of this occasion

Add parameter is of type object

To sort the hash table
    Sort here in the definition of the hash table is the key/value key to rearrange the key according to certain rules, but in fact this definition is not realized, because we cannot directly in the Hashtable to key are rearranged, if Hashtable is required to provide the output of a rule, can adopt a flexible approach:

ArrayList akeys=new ArrayList(ht.Keys); //Don't forget to import System.Collections
akeys.Sort(); //Sorted in alphabetical order
foreach(string skey in akeys)
{
   Console.Write(skey + ":");
Console.WriteLine(ht[skey]);//After sorting the output
}
1 Hashtable ht = new Hashtable(); //Create aHashtableExample 2 ht.Add("E", "e");//Add tokey/valueKey value pairs 3 ht.Add("A", "a"); 4 ht.Add("C", "c"); 5 ht.Add("B", "b"); 6 string s = (string)ht["A"]; 7 if (ht.Contains("E")) //To judge whether the hash table contains a specific key,The return value istrueOrfalse 8 Console.WriteLine("the E key:exist"); 9 ht.Remove("C");//Remove akey/valueKey value pairs 10 Console.WriteLine(ht["A"]);//Here the outputa 11 ht.Clear();//Remove all elements 12 Console.WriteLine(ht["A"]); //There will not be any output 13 Console.ReadKey();

NameValueCollection:

System.Collections.Specialized.NameValueCollection is the most interesting place lies in that it can contain multiple projects associated with a key value (to allow the same key, value can be a comma together), it and other built-in set difference. In addition, it is similar to the function of HashTable, the advantages and disadvantages of each project according to the Hashi code is derived from the key of project scheduling and also has the similar. Use: write a custom control keys with the general store

ListDictionary and HybridDictionary:

ListDictionary and HybridDictionary belong to System.Collections.Specialized. They are in accordance with the only key principles to organize the project, and have achieved IDictionary and ICollection . ListDictionary is stored in a list of ways in the internal project proposals, set to grow more than 10 projects are not in. HybridDictionary uses an internal chain table (actually ListDictionary) as a small set, when the set becomes large enough (more than 10 projects) that linked list implementation efficiency will be converted to HashTable.

StringCollection and StringDictionary:

System.Collections.Specialized.StringCollection and System.Collections.Specialized.StringDictionary are stored on the collection of strings are optimized. StringCollection implementation of the IList and ICollection and is essentially ArrayList, only the strong type only accepts a string. Application of the ideal of StringCollection is a small amount of data updated frequently or increased, while StringDictionary is the most applicable to often do not increase the project such as HashTable, large data set.

SortedList:

System.Collections.SortedList, It implements the IDictionary interface and the ICollection interface, is the most basic sorting collection, and Vb6 Collection object is very similar. SortedList storage objects and in accordance with the associated key to these storage object ordering. They also support the index number and the key object to retrieve only the built-in.NET set, similar to the hash table, the difference is that Key array in SortedList sorted

1 SortedList sl = new SortedList(); 2 sl["c"] = 41; 3 sl["a"] = 42; 4 sl["d"] = 11; 5 sl["b"] = 13; 6 7 foreach (DictionaryEntry element in sl) 8 { 9 string s = (string)element.Key; 10 int i = (int)element.Value; 11 Console.WriteLine("{0},{1}", s, i); 12 }

Dictionary generic collection

The most common use of generics is generic collection, System.Collections.Generic namespace contains some generic collection classes based on, use generic collection class can provide type safety higher, and higher performance, avoid package repeated non generic collection.
Many non generic collection class has a corresponding generic collection classes, the following is a common non generic collection classes and the corresponding generic collection classes:
Non generic collection classes Generic collection classes
ArrayList List<T>
HashTable DIctionary<T>
Queue Queue<T>
Stack Stack<T>
SortedList SortedList<T>


We use more non generic collection classes are class ArrayList and class HashTable. We often use HashTable to store will be written to the database or return information, In between to continue to the type conversion, Adds a package burden, If the Dictionary< with our manipulation of the data type to determine the relative; TKey, TValue> the collection class to store data more convenient, E.g. we need in e-commerce site to store the user's shopping cart information (trade name, The number of goods when the corresponding), Can use Dictionary<string, int> to store shopping cart information, Without the need for any type of conversion.

Here is a simple example, including the statements, filling key value pairs, remove the key value pairs, traverse the key value pair
1 Dictionary<string, string> myDic = new Dictionary<string, string>(); 2 myDic.Add("aaa", "111"); 3 myDic.Add("bbb", "222"); 4 myDic.Add("ccc", "333"); 5 myDic.Add("ddd", "444"); 6 //If you add the key already exists, addMethod will throw an exception 7 try 8 { 9 myDic.Add("ddd", "ddd"); 10 } 11 catch (ArgumentException ex) 12 { 13 Console.WriteLine("This key already exists: " + ex.Message); 14 } 15 //Solveadd()The unusual method is usedContainsKey()Method to determine whether the key is present 16 if (!myDic.ContainsKey("ddd")) 17 { 18 myDic.Add("ddd", "ddd"); 19 } 20 else 21 { 22 Console.WriteLine("This key already exists: "); 23 24 } 25 26 //While the use of index is negative, If built already exists, Will modify the key value, And no exception is 27 myDic["DDD"] = "DDD"; 28 "EEE myDic["] = "555"; 2930 // use the index to value, If the key does not exist an exception is thrown 31 try 32 { 33 Console.WriteLine("There is no key\"fff\"Key to: " + myDic["fff"]); 34 } 35 catch (KeyNotFoundException ex) 36 { 37 Console.WriteLine("Not found the key to throw an exception: " + ex.Message); 38 } 39 //Solution is to use the above abnormalContarnsKey() To determine the time of key, If you often take health is worth of the best TryGetValueMethod to obtain the corresponding value in the set 40 string value = ""; 41 if (myDic.TryGetValue("fff", out value)) 42 { 43 Console.WriteLine("There is no key\"fff\"Key to: " + value); 44 } 45 else 46 { 47 Console.WriteLine("The keys of the key not found"); 48 } 49 50 //The followingforeach To traverse the key value pair 51 //Generic structure is used to store the key value pair 52 foreach (KeyValuePair<string, string> kvp in myDic) 53 { 54 Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value); 55 } 56 //Gets the worthy of collection 57 foreach (string s in myDic.Values) 58 { 59 Console.WriteLine("value={0}", s); 60 } 61 //Another way to get it 62 Dictionary<string, string>.ValueCollection values = myDic.Values; 63 foreach (string s in values) 64 { 65 Console.WriteLine("value={0}", s); 66 }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Leif at November 18, 2013 - 9:34 PM