C × basic knowledge series - 3 set array

Keywords: C# less Attribute Java Programming

Let's briefly introduce the collection. Generally speaking, it's a scheme used to store multiple data. For example, we are a company's warehouse management. The company has a lot of goods that need to be managed. There are similar goods and different kinds of goods. In a word, they are many and messy. If we manage the warehouse according to the concept of Set, then Array is to put a pile of neat codes in a certain place of the warehouse, as is the common list; Set is to have such a shelf in the warehouse, each kind of goods can only be put on one shelf, once more than one kind of goods has collapsed; Dictionary dictionary is to put them on one shelf randomly, and then find a book to record the storage position of each goods.

1. Main assembly

The C /. Net framework provides many interesting collection classes, such as arrays, lists, linked lists, sets, dictionaries, etc. Among them, the array is a part of the language, and I don't think it belongs to the collection class strictly. In C ා development, the commonly used collections are array, List class, Set interface, Dictionary class, Queue class, LinkedList class, etc., and the other ones are not high.
Different from other (java) languages, the List of C ා is a class, not an interface, and the interface is IList, but this interface is of little significance. When using IList, it tends to use IEnumerable more. This is mainly because IEnumerable has Linq's support, and the two methods are basically the same. Where IList can be used, IEnumerable can be used.

1.1 Array

Array, the basic part of a collection, has the main feature that once initialized, you cannot add or delete elements to the array itself again. C ා although some extended methods are added to modify the array, new array objects are basically returned.

1.1.1 initialization

The initialization of an array requires a specified size, which can be specified or implicitly specified.

// Display the specified type and size, specific element subsequent assignment
string[] strArr = new string[10]; 
//Specifies the type and assigns values to the elements. The specific size is automatically inferred by the compiler
string[] strArr1 = new string[]{"1","2","3","4","5","6","7","8","9","10"};
// Type and size are inferred by the compiler
string[] strArr2 = new []{"1","2","3","4","5","6","7","8","9","10"}; 

1.1.2 common methods

  1. Access and assignment
    An array can access its elements through subscripts, which start from 0 and represent 0 bits. The code is as follows:
string item0 = strArr[0]; //Remove "1".
string item2 = strArr[2]; // Remove "3".
strArr[0] = "3"; // strArr = {"3","2","3","4","5","6","7","8","9","10"}
  1. Get length
int length = strArr.Length;// Get the length of an integer
//Gets the length of a long integer. For a very large array, the length may exceed the maximum value of int
long longLength = strArr.LongLength;
  1. Cyclic iteration
// Normal for loop
for(int i = 0;i < strArr.Length;i++)
{
	string it = strArr[i];
}
// foreach cycle
foreach(string it in strArr)
{
	// Cycle in turn, no subscript required, faster operation
}

1.1.3 uncommon but useful methods

  1. CopyTo copy to

    public void CopyTo(Array array, int index);
    public void CopyTo(Array array, long index);
    

    Parameter Description: the array to which array needs to be copied, and the starting subscript of index target array

    Method description: copy the elements of the source array to the position of array starting from index subscript

    string[] strArr1 = new string[]{"1","2","3","4","5","6","7","8","9","10"};
    string[] strArr3 = new string[10];
    strArr1.CopyTo(strArr3, 0); //strArr3 = {"1","2","3","4",'5","6","7","8","9","10"}
    
    

    Note that the length of strArr3 cannot be less than index + strArr1.Length

  2. Sort sorting

    This method is not an Array object method, but a static method provided by Array.

    int[] arr1 = new[] {1, 9, 28, 5, 3, 6, 0, 12, 44, 98, 4, 2, 13, 18, 81, 92};
    Array.Sort(arr1);//0,1,2,3,4,5,6,9,12,13,18,28,44,81,92,98
    

    It is worth noting that this method operates directly on the array, so no new array will be returned.

  3. To List to List

As the name implies, convert an Array object to a List object. It should be noted that the length of the converted List cannot be changed.
4. Clone() gets a shallow copy of the array object

Gets a shallow copy array object of the object.

As for other Array classes and objects, there are many interesting methods, but they are usually used less frequently. I won't introduce them here. I need to introduce them later.

1.2 List

List list is a generic class, and the generic type represents < T >, where T represents the element type stored in the list, and T represents the instantiatable type in C ා. For a more detailed description of generics, let's go back to the list. There is an array object in the list, and the list has two private variables: one is the list capacity, that is, the size of the internal array; the other is the number of stored elements, which is obtained by Count.
The List list implements the Add and Remove operations through the number of elements. When the number of elements changes due to the List object operation, the capacity will be recalculated. If the existing capacity does not meet the needs of subsequent operations, the existing array will be expanded.

1.2.1 initialization

List<string> list = new List<string>();// Initialize an empty list
List<string> list1 = new List<string>{"12", "2"};//Initializing a list of two elements
list1 = new List<string>(100);//Initializes an empty list and specifies that the initial capacity of the list is 100
list = new List<string>(list1);// Initializing a list with a List/Array

1.2.2 common methods

  1. Count or LongCount get the number of elements

    Count means to get the quantity value of an int type, and LongCount means to get the quantity value of a long type. In general, the results returned by the two methods are the same. However, if the number of elements in the list exceeds the maximum allowed by int, using count directly will cause data overflow, and LongCount is needed.

  2. Access element / modify element

    The list operation of C ා is very simple, just like the operation of array.

    string str = list1[0];//Gets the first element of list1, the element with the subscript 0
    

list1[2] = "233"; / / set the third element of list1 to "233", that is, the element with the subscript of 2. Here, it is assumed that list1 has at least three elements
```
It should be noted that if the given subscript exceeds the index value range of the List object, ArgumentOutOfRangeException will be reported. The judgment method is subscript > = count. If it is satisfied, it will cross the boundary.
3. Add or AddRange to the end of the list

Add elements to the end of the List, ` add 'adds one, ` AddRange' adds a group, and supports arrays and lists.

```c#
List < string > List = new list < string > (); / / initialize an empty list
list.Add("12");//list = {"12"}
List<string> list1 = new List<string>{"14", "2"};
list.AddRange(list1);// list = {"12","14","2"}
```
  1. Insert(int index, T item) or insertrange (int index, IEnumerable < T > items) insert

    • Insert(int index,T item) inserts an element at the index subscript. The subscript and the elements after the subscript move backward in turn
    • Insertrange (int index, IEnumerable < T > items) inserts a set of elements at the index subscript, and the subscript and subsequent elements move backward in turn

    Example:

    List<int> arr1 = new List<int>{1, 9, 28, 5, 3, 6, 0, 12, 44, 98, 4, 2, 13, 18, 81, 92};
    arr1.Insert(3,37);// The element with the subscript of arr1 = 1,9,28,37,5,3,6,0,12,44,98,4,2,13,18,81,92 becomes 37, and then the element moves backward
    
    List<int> arr1 = new List<int>{1, 9, 28, 5, 3, 6, 0, 12, 44, 98, 4, 2, 13, 18, 81, 92};
    List<int> arr2 = new List<int>{2,3,4,5};
    arr1.InsertRange(2,arr2);//The change of elements with subscript 2 can be found clearly when Arr1 = 1,9,2,3,4,5,28,5,3,6,0,12,44,98,4,2,13,18,81,92
    
  2. Contains(T item) contains
    Returns a result of type Boolean, true if included, false if not included

    List<int> arr2 = new List<int>{2,3,4,5};
    arr2.Contains(8);//false
    arr2.Contains(3);//true
    
  3. Remove(T item) removes the specified element

    List<int> arr2 = new List<int>{2,3,4,5};
    arr2.Remove(3);// arr2 = 2,4,5
    arr2.Remove(6);//arr2 = 2,4,5
    

    It is worth noting that if you delete a nonexistent element, no error will be reported and the list will not change.

  4. RemoveAt(int index) removes the element at the subscript

    List<int> arr2 = new List<int>{2,3,4,5};
    arr2.RemoveAt(1);//arr2 = 2,4,5
    

    An exception will be thrown if the removed subscript exceeds that of the last element of the list

  5. Removeane (IEnumerable < T > items) removes a set of elements

    Consistent with Remove(T item), if the element to be removed is not in the list, the list element will not change.

    List<int> arr1 = new List<int>{1, 9, 28, 5, 3, 6, 0, 12, 44, 98, 4, 2, 13, 18, 81, 92};
    List<int> arr2 = new List<int>{2,3,4,5};
    arr1.RemoveRange(arr2);
    
  6. GetRange(int index,int count)

    Get a sublist from the list. Start with index, get count elements. If the remaining elements from index in the source list are less than count, an error will be reported.

1.2.3 uncommon but useful methods

  1. Clear() delete all elements

    Clear the list. After calling the method, the list will not contain any elements

  2. Reverse() transfer order

    Arrange the list from end to end

  3. IndexOf(T item) find subscript

    Find the subscript of the element in the list. If the element is not found, return - 1

  4. Sort() sort

    Sort the list. After calling the method, a sorting result will be returned according to the default sorting method

1.3 Set set

C ා does not set a separate class for set. On the one hand, it is due to the low exposure rate of set, on the other hand, it is also due to the mechanism of set itself. Set collection cannot contain duplicate elements. If you try to store duplicate element collection elements, nothing will change.
The order of the elements in the Set set is not necessarily the same as the order in which they are stored. Because the Set set is stored in disorder for users.
Our common Set sets are HashSet < T > and sortset < T >, while other Set related classes are even rarer. At least not in my development experience of more than 5 years.

1.3.1 HashSet < T > and sortset < T >

  • HashSet, commonly known as Hash Set or Hash Set, internally uses Hash value as the uniqueness verification of elements, that is, the HashCode() method of the calling object is the source of Hash value.
  • SortSet, as the name implies, sorts a set. It sorts elements once every time it is inserted

1.3.2 common points

  1. Initialization

    The same thing is that there are several initialization methods

    Set<T> set = new HashSet<T>();// =New sortset < T > (); initializes an empty set
    //Initialize with a collection object
    Set<T> set1 = new HashSet<T>(IEnumerable<T> items);// = new SortSet<T>(IEnumerable<T> items); 
    Set<T> set2 = new HashSet<T>(){T t1, T t2, T t3};// Same as the previous one
    
  2. Additive elements

    set1.Add(item);// Collection only supports adding a single element, but multiple elements can be added through set operation
    
  3. Removing Elements

    set1.Remove(item);//Delete the elements in the set equal to the item judgment
    
  4. Access element

    It should be noted that C ා does not support the subscript access method to get the elements in the Set, because the index location is of little significance to the Set and has no operational significance.

    foreach (var item in set1)
    {
    	// operation
    }
    

    Set can only access elements through traversal, not through Get or subscript operation. foreach cycle will be introduced in the next "C basic knowledge series".

  5. Set operation

    1. Union with and

      SortedSet<int> set = new SortedSet<int>{1,0,29,38,33,48,17};
      set.UnionWith(new []{5,57,8,4,3,1,0,33}); // set = 0,1,3,4,5,8,17,29,33,38,48,57
      

      By passing in a collection object, set the collection as the union of two sets, that is to say, take the sum of areas a, B and C in the above figure

    2. ExceptWith poor

      SortedSet<int> set = new SortedSet<int>{1,0,29,38,33,48,17};
      set.ExceptWith(new []{5,57,8,4,3,1,0,33}); // set =17,29,38,48
      

      Pass in A set, remove the elements belonging to both sets from the set, and retain the elements only existing in the set, that is, take part A of the elements in the figure above

    3. Intersect with

      SortedSet<int> set = new SortedSet<int>{1,0,29,38,33,48,17};
      set.ExceptWith(new []{5,57,8,4,3,1,0,33}); // set =0,1,33
      

      Pass in a set, keep the same elements in the set and the passed in set, that is to say, take part B in the figure above

    4. SymmetricExceptWith coset

      SortedSet<int> set = new SortedSet<int>{1,0,29,38,33,48,17};
      set.SymmetricExceptWith(new []{5,57,8,4,3,1,0,33});//set= 3,4,5,8,17,29,38,48,57
      

      Pass in a set, keep the different elements in the set and the incoming set, that is, take the A+C part of the above figure.

  6. Contains contains

    Judge whether the collection contains the target element, and return true/false

    SortedSet<int> set = new SortedSet<int>{1,0,29,38,33,48,17};
    set.Contains(1);// true
    

1.3.3 differences

  1. Initialization
    • HashSet < T > supports passing in a custom equality comparer, which needs to return a bool value; you can specify the starting capacity
    • Sortset < T > supports passing in a custom size comparer, which returns an int value; the starting capacity cannot be specified
  2. Other
    Comparer property: SortSet can get a size comparer; HashSet can get an equality comparer

1.4 Dictionary

Dictionary dictionary, just like its name, needs to specify two types, one as index key and one as data value. Just like a dictionary, every entry has only one word index, but synonyms can appear. Of course, as my extensive and profound Chinese, there will be phrases with different sounds of the same word, but once the sounds and words are combined as an index, only one entry will appear.
Therefore, dictionaries are used in the same way as dictionaries, to access and manipulate data through indexes.

1.4.1 initialization

There are several ways to initialize a Dictionary:

Dictionary<string, int> dict = new Dictionary<string, int>();// Key is string, value is int type
Dictionary<string,int> dict1 = new Dictionary<string, int>(10);// The specified initial capacity is 10
Dictionary<string,int> dict2 = new Dictionary<string, int>()
{
	{"1",1},
	{"2",2}
};// Create a dictionary object with {key,value} in braces, and include these key value pairs

// Pass in a dictionary object and create a dictionary based on the passed in object
Dictionary<string,int> dict3 = new Dictionary<string, int>(dict2);

1.4.2 common methods

  1. Additive elements

    Dictionary<string, int> dict = new Dictionary<string, int>();
    // Method 1
    dict.Add("1",2);//Add a key value pair with a key of "1" and a value of 2.
    //Method two
    //Dictionaries can add or update key values through subscripts in the form of lists,
    //Unlike a list, however, the subscript of a dictionary is a string
    dict["2"] = 4;// If 2 in dict has a value, it will be updated to 4. If not, the value corresponding to 2 will be set to 4
    
  2. Get elements

    Dictionary<string, int> dict = new Dictionary<string, int>();
    /*
    Omit data filling phase
    */
    int value = dict["2"]; // value = 4
    // If data with index '2' does not exist in Dictionary
    // System.Collections.Generic.KeyNotFoundException will be thrown
    

    There is also a TryGetValue method in the Dictionary of C ා, which can be used to try to obtain. Its usage method is as follows:

    int obj = 0;
    boolean isContains = dict.TryGetValue("3", out obj);
    // Method returns whether the dict contains the key "3". If there is obj, the corresponding value in the dict is stored. If there is no obj, the value of obj is returned false without changing
    
  3. Count

    Gets the number of key value pairs in the Dictionary.

    int count = dict.Count;
    

    Dictionaries do not have the LongCount attribute, because for dictionaries, storing data needs to be equal to the Key. If a large amount of data is stored, it will have an impact on data access and operation efficiency.

  4. Keys

    Get all the keys in the Dictionary and return a KeyCollection object. You don't need to care what type it is. You can simply treat it as a HashSet where the keys are stored.

  5. ContainsKey()

    Include key: it is usually used together with getting elements. You can first determine whether there is a key in the Dictionary, and then carry out subsequent operations.

  6. Remove()

    Delete the element corresponding to the key in the Dictionary, and an error will be reported if you access it again after deletion. If you delete a non-existent element, you will return flash.
    Operation example:

    Dictionary<string,int> dict = new Dictionary<string, int>();
    //Omit assignment
    bool result = dict.Remove("2");// If the dict contains an element with key "2", the result is true, otherwise it is false
    

    Another way:

    int value = 0;
    bool result = dict.Remove("2", out value);
    // If the dict contains an element with key "2", the result is false and the value is the corresponding value
    

1.4.3 uncommon but useful methods

  1. ContainsValue()

    Whether to include a value is the same as the use of ContainsKey, only traversing the value; not useful.

  2. Values

    The collection of obtained values is similar to KeyValues.

2. Traditional set (non generic)

The traditional collections of C ා are basically stored in the System.Collections namespace, which can be viewed in detail Official documents of Microsoft . There are not many collection classes in this namespace, but the interface specifications of C ා collection system are defined in this namespace.

2.1 introduction to common types

  1. The non generic version of ArrayList List is consistent with the List operation method, but the return value is of Object type

  2. SortedList is a sorted set of key value pairs. I haven't used it, but the official gives the following example:

    using System;
    using System.Collections;
    public class SamplesSortedList  {
    
    	 public static void Main()  {
    
    			// Creates and initializes a new SortedList.
    			SortedList mySL = new SortedList();
    			 mySL.Add("Third", "!");
    			 mySL.Add("Second", "World");
    			 mySL.Add("First", "Hello");
    
    			// Displays the properties and values of the SortedList.
    			Console.WriteLine( "mySL" );
    			Console.WriteLine( "  Count:    {0}", mySL.Count );
    			Console.WriteLine( "  Capacity: {0}", mySL.Capacity );
    			Console.WriteLine( "  Keys and Values:" );
    			PrintKeysAndValues( mySL );
    	 }
    
    	 public static void PrintKeysAndValues( SortedList myList )  {
    			Console.WriteLine( "\t-KEY-\t-VALUE-" );
    			for ( int i = 0; i < myList.Count; i++ )  {
    				 Console.WriteLine( "\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i) );
    			}
    			Console.WriteLine();
    	 }
    }
    
  3. HashTable represents a collection of key / value pairs organized according to the key's Hash code. The structure of HashTable is similar to but different from Dictionary. Its key value is stored with Hash value. Here is the official sample code:

    using System;
    using System.Collections;
    
    class Example
    {
    		public static void Main()
    		{
    				// Create a new hash table.
    				//
    				Hashtable openWith = new Hashtable();
    
    				// Add some elements to the hash table. There are no 
    				// duplicate keys, but some of the values are duplicates.
    				openWith.Add("txt", "notepad.exe");
    				openWith.Add("bmp", "paint.exe");
    				openWith.Add("dib", "paint.exe");
    				openWith.Add("rtf", "wordpad.exe");
    
    				// The Add method throws an exception if the new key is 
    				// already in the hash table.
    				try
    				{
    						openWith.Add("txt", "winword.exe");
    				}
    				catch
    				{
    						Console.WriteLine("An element with Key = \"txt\" already exists.");
    				}
    
    				// The Item property is the default property, so you 
    				// can omit its name when accessing elements. 
    				Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
    
    				// The default Item property can be used to change the value
    				// associated with a key.
    				openWith["rtf"] = "winword.exe";
    				Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
    
    				// If a key does not exist, setting the default Item property
    				// for that key adds a new key/value pair.
    				openWith["doc"] = "winword.exe";
    
    				// ContainsKey can be used to test keys before inserting 
    				// them.
    				if (!openWith.ContainsKey("ht"))
    				{
    						openWith.Add("ht", "hypertrm.exe");
    						Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]);
    				}
    
    				// When you use foreach to enumerate hash table elements,
    				// the elements are retrieved as KeyValuePair objects.
    				Console.WriteLine();
    				foreach( DictionaryEntry de in openWith )
    				{
    						Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
    				}
    
    				// To get the values alone, use the Values property.
    				ICollection valueColl = openWith.Values;
    
    				// The elements of the ValueCollection are strongly typed
    				// with the type that was specified for hash table values.
    				Console.WriteLine();
    				foreach( string s in valueColl )
    				{
    						Console.WriteLine("Value = {0}", s);
    				}
    
    				// To get the keys alone, use the Keys property.
    				ICollection keyColl = openWith.Keys;
    
    				// The elements of the KeyCollection are strongly typed
    				// with the type that was specified for hash table keys.
    				Console.WriteLine();
    				foreach( string s in keyColl )
    				{
    						Console.WriteLine("Key = {0}", s);
    				}
    
    				// Use the Remove method to remove a key/value pair.
    				Console.WriteLine("\nRemove(\"doc\")");
    				openWith.Remove("doc");
    
    				if (!openWith.ContainsKey("doc"))
    				{
    						Console.WriteLine("Key \"doc\" is not found.");
    				}
    		}
    }
    
    /* This code example produces the following output:
    
    An element with Key = "txt" already exists.
    For key = "rtf", value = wordpad.exe.
    For key = "rtf", value = winword.exe.
    Value added for key = "ht": hypertrm.exe
    
    Key = dib, Value = paint.exe
    Key = txt, Value = notepad.exe
    Key = ht, Value = hypertrm.exe
    Key = bmp, Value = paint.exe
    Key = rtf, Value = winword.exe
    Key = doc, Value = winword.exe
    
    Value = paint.exe
    Value = notepad.exe
    Value = hypertrm.exe
    Value = paint.exe
    Value = winword.exe
    Value = winword.exe
    
    Key = dib
    Key = txt
    Key = ht
    Key = bmp
    Key = rtf
    Key = doc
    
    Remove("doc")
    Key "doc" is not found.
     */
    

    Although the C ා framework retains non generic collection elements, it is not recommended to use non generic collection for development.

3 some unusual set classes

In addition to the above mentioned collection classes, C ා also sets some collection classes that are not commonly used in development but useful in specific situations.

3.1 Queue < T > and Queue

These two classes are a pair, a generic class and a non generic class. The Chinese name of this type is queue, as its name implies, the queue emphasizes a first in, first out, so every time the elements of the queue are taken from the beginning and stored at the end of the queue.
The operation code is as follows:

  1. Join queue

    Queue queue = new Queue();
    queue.Enqueue(1);
    queue.Enqueue("2");
    
    Queue<string> queue1 = new Queue<string>();
    queue1.Enqueue("stri");//
    
  2. Read element of team leader
    There are two types of reads:

    • Read without removing elements:

      object obj= queue.Peek();
      string str = queue.Peek();
      
    • Read and remove elements:

      object obj = queue.Dequeue();
      string str = queue.Dequeue();
      
    1. Count gets the number of elements

3.2 LinkedList<T>

LinkedList, linked List. Unlike List, the LinkedList element is a LinkedListNode object, which has four properties, namely List
-Point to the list object, Previous to the Previous object if any, and Next to the Next object if any. Therefore, according to the attribute of the element, we can find the working mode of the linked list. The linked list is like a chain. One element is divided into three parts, one points to the Previous element, one is used to store the value, and the other points to the Next element, as shown in the following figure

So it can be obviously found that LinkedList is faster than normal in random insertion, because it does not need to maintain an array, but it is much slower in search and coordinate operation.
LinkedList briefly introduces so many things. You can take a look at some of its common operations:

  1. First first element

    Get first element

  2. Last element

    Get last element

  3. AddAfter/AddBefore
    Insert data after / before a node
    The following parameter lists are supported:

    • (LinkedListNode node, T value)
    • (LinkedListNode node, LinkedListNode newNode)

    The first parameter represents the node location to insert, and the second represents the node / element to insert. The first parameter will verify whether it belongs to the linked list. If it does not, an exception will be thrown. The second can be a value or an initialized node object. If it is a node object, judge whether it belongs to other linked lists. If it is other linked lists, throw an exception.

  4. AddFirst/AddLast

    To add elements to the head or tail, you can use LinkedListNode or add values.

  5. Remove

    Delete, you can pass a node or the value stored in the node to be deleted.

  6. RemoveFirst/RemoveLast
    Delete the first node, delete the last node, without parameters

Here are some official examples of Microsoft

using System;
using System.Text;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create the link list.
        string[] words =
            { "the", "fox", "jumps", "over", "the", "dog" };
        LinkedList<string> sentence = new LinkedList<string>(words);
        Display(sentence, "The linked list values:");
        Console.WriteLine("sentence.Contains(\"jumps\") = {0}",
            sentence.Contains("jumps"));

        // Add the word 'today' to the beginning of the linked list.
        sentence.AddFirst("today");
        Display(sentence, "Test 1: Add 'today' to beginning of the list:");

        // Move the first node to be the last node.
        LinkedListNode<string> mark1 = sentence.First;
        sentence.RemoveFirst();
        sentence.AddLast(mark1);
        Display(sentence, "Test 2: Move first node to be last node:");

        // Change the last node to 'yesterday'.
        sentence.RemoveLast();
        sentence.AddLast("yesterday");
        Display(sentence, "Test 3: Change the last node to 'yesterday':");

        // Move the last node to be the first node.
        mark1 = sentence.Last;
        sentence.RemoveLast();
        sentence.AddFirst(mark1);
        Display(sentence, "Test 4: Move last node to be first node:");

        // Indicate the last occurence of 'the'.
        sentence.RemoveFirst();
        LinkedListNode<string> current = sentence.FindLast("the");
        IndicateNode(current, "Test 5: Indicate last occurence of 'the':");

        // Add 'lazy' and 'old' after 'the' (the LinkedListNode named current).
        sentence.AddAfter(current, "old");
        sentence.AddAfter(current, "lazy");
        IndicateNode(current, "Test 6: Add 'lazy' and 'old' after 'the':");

        // Indicate 'fox' node.
        current = sentence.Find("fox");
        IndicateNode(current, "Test 7: Indicate the 'fox' node:");

        // Add 'quick' and 'brown' before 'fox':
        sentence.AddBefore(current, "quick");
        sentence.AddBefore(current, "brown");
        IndicateNode(current, "Test 8: Add 'quick' and 'brown' before 'fox':");

        // Keep a reference to the current node, 'fox',
        // and to the previous node in the list. Indicate the 'dog' node.
        mark1 = current;
        LinkedListNode<string> mark2 = current.Previous;
        current = sentence.Find("dog");
        IndicateNode(current, "Test 9: Indicate the 'dog' node:");

        // The AddBefore method throws an InvalidOperationException
        // if you try to add a node that already belongs to a list.
        Console.WriteLine("Test 10: Throw exception by adding node (fox) already in the list:");
        try
        {
            sentence.AddBefore(current, mark1);
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine("Exception message: {0}", ex.Message);
        }
        Console.WriteLine();

        // Remove the node referred to by mark1, and then add it
        // before the node referred to by current.
        // Indicate the node referred to by current.
        sentence.Remove(mark1);
        sentence.AddBefore(current, mark1);
        IndicateNode(current, "Test 11: Move a referenced node (fox) before the current node (dog):");

        // Remove the node referred to by current.
        sentence.Remove(current);
        IndicateNode(current, "Test 12: Remove current node (dog) and attempt to indicate it:");

        // Add the node after the node referred to by mark2.
        sentence.AddAfter(mark2, current);
        IndicateNode(current, "Test 13: Add node removed in test 11 after a referenced node (brown):");

        // The Remove method finds and removes the
        // first node that that has the specified value.
        sentence.Remove("old");
        Display(sentence, "Test 14: Remove node that has the value 'old':");

        // When the linked list is cast to ICollection(Of String),
        // the Add method adds a node to the end of the list.
        sentence.RemoveLast();
        ICollection<string> icoll = sentence;
        icoll.Add("rhinoceros");
        Display(sentence, "Test 15: Remove last node, cast to ICollection, and add 'rhinoceros':");

        Console.WriteLine("Test 16: Copy the list to an array:");
        // Create an array with the same number of
        // elements as the inked list.
        string[] sArray = new string[sentence.Count];
        sentence.CopyTo(sArray, 0);

        foreach (string s in sArray)
        {
            Console.WriteLine(s);
        }

        // Release all the nodes.
        sentence.Clear();

        Console.WriteLine();
        Console.WriteLine("Test 17: Clear linked list. Contains 'jumps' = {0}",
            sentence.Contains("jumps"));

        Console.ReadLine();
    }

    private static void Display(LinkedList<string> words, string test)
    {
        Console.WriteLine(test);
        foreach (string word in words)
        {
            Console.Write(word + " ");
        }
        Console.WriteLine();
        Console.WriteLine();
    }

    private static void IndicateNode(LinkedListNode<string> node, string test)
    {
        Console.WriteLine(test);
        if (node.List == null)
        {
            Console.WriteLine("Node '{0}' is not in the list.\n",
                node.Value);
            return;
        }

        StringBuilder result = new StringBuilder("(" + node.Value + ")");
        LinkedListNode<string> nodeP = node.Previous;

        while (nodeP != null)
        {
            result.Insert(0, nodeP.Value + " ");
            nodeP = nodeP.Previous;
        }

        node = node.Next;
        while (node != null)
        {
            result.Append(" " + node.Value);
            node = node.Next;
        }

        Console.WriteLine(result);
        Console.WriteLine();
    }
}

//This code example produces the following output:
//
//The linked list values:
//the fox jumps over the dog

//Test 1: Add 'today' to beginning of the list:
//today the fox jumps over the dog

//Test 2: Move first node to be last node:
//the fox jumps over the dog today

//Test 3: Change the last node to 'yesterday':
//the fox jumps over the dog yesterday

//Test 4: Move last node to be first node:
//yesterday the fox jumps over the dog

//Test 5: Indicate last occurence of 'the':
//the fox jumps over (the) dog

//Test 6: Add 'lazy' and 'old' after 'the':
//the fox jumps over (the) lazy old dog

//Test 7: Indicate the 'fox' node:
//the (fox) jumps over the lazy old dog

//Test 8: Add 'quick' and 'brown' before 'fox':
//the quick brown (fox) jumps over the lazy old dog

//Test 9: Indicate the 'dog' node:
//the quick brown fox jumps over the lazy old (dog)

//Test 10: Throw exception by adding node (fox) already in the list:
//Exception message: The LinkedList node belongs a LinkedList.

//Test 11: Move a referenced node (fox) before the current node (dog):
//the quick brown jumps over the lazy old fox (dog)

//Test 12: Remove current node (dog) and attempt to indicate it:
//Node 'dog' is not in the list.

//Test 13: Add node removed in test 11 after a referenced node (brown):
//the quick brown (dog) jumps over the lazy old fox

//Test 14: Remove node that has the value 'old':
//the quick brown dog jumps over the lazy fox

//Test 15: Remove last node, cast to ICollection, and add 'rhinoceros':
//the quick brown dog jumps over the lazy rhinoceros

//Test 16: Copy the list to an array:
//the
//quick
//brown
//dog
//jumps
//over
//the
//lazy
//rhinoceros

//Test 17: Clear linked list. Contains 'jumps' = False
//

3.3 Stack < T > and Stack

Stack's extensive translation is stack, a kind of last in, first out collection. In some special scenes, it is widely used.
Stack has two very important methods pop and Push, out / in. Pop takes the last element, exits the stack, and Push pushes an element into the stack.
For details, please refer to Official documents

4 collection related namespace

There are some other namespaces in C ා s collection, but they are not frequently used in actual development and can be viewed on demand.

4.1 System.Collections.Concurrent thread safety

This namespace provides a series of thread safe collection classes. When there is a collection of multi-threaded operations, the collection of this namespace should be used. The name corresponds to the commonly used class in 11, but only several collection classes such as ConcurrentDictionary<TKey, TValue>, ConcurrentQueue<T>, ConcurrentStack<T> are provided. You can view the details Official documents

4.2 System.Collections.Immutable

Namespace contains the interfaces and classes used to define immutable collections. If you need to use this namespace, you need to use NuGet to download.

    • Share a collection so that its consumers can ensure that the collection never changes.
  • Provides implicit thread safety in multithreaded applications (no locks are required to access collections).
  • Follow functional programming practices.
  • Modify the collection during enumeration, while ensuring that the original collection does not change.

Please pay attention to more My blog

Posted by trooper on Fri, 27 Mar 2020 05:51:47 -0700