[Reading Notes] C # chapter 10 of advanced programming,

Source: Internet
Author: User

[Reading Notes] C # chapter 10 of advanced programming,

(1) Overview

The array size is fixed. If the number of elements is dynamic, use the collection class.

List <T> is a collection class equivalent to an array. There are other types of collections: queue, stack, linked list, dictionary, and set.

 

 

(2) List

1. Create a list

By calling the default constructor, you can create a list object. In the generic class List <T>, you must specify a type for the declared value of the List. Use the default constructor to create an empty list. After an element is added to the list, the capacity of the list will expand. After each element is added to the list, the capacity will be reset to twice the original capacity.

Example:

List<string> strList = new List<string>();

If the capacity of the list changes, the entire set will be re-allocated to a new memory block. You can use the Capacity attribute to obtain and set the Capacity of a set.

Example:

strList.Capacity = 100;

The number of elements in the set can be read using the Count attribute.

Example:

var count= strList.Count;

You can call TrimExcess () to remove unnecessary capacity.

Example:

strList.TrimExcess();

Note that the number of elements exceeds 90% of the capacity, and the TrimExcess () method does nothing.

 

(1) set initial values

You can also assign values to the set by using the set Initial Value Setting item.

Example:

List<string> strList = new List<string>() { "zhangsan", "lisi" };

 

(2) Add Elements

You can use the Add () method to Add elements to the list.

Example:

strList.Add("zhangsan");

Using the AddAange () method, you can add multiple elements to the set at a time.

Example:

strList.AddRange(new string[] { "lisi", "wangmazi" });strList.AddRange(new List<string> { "zhaoliu", "qianqi" });

 

(3) Insert elements

You can use the Insert () method to Insert an element at a specified position.

Example:

strList.Insert(0, "begin");

Using InsertRange () provides the ability to insert a large number of elements.

Example:

strList.InsertRange(1, new string[] { "zhang", "li", "wang" });

 

(4) access elements

All classes that implement the IList <T> and IList interfaces provide an indexer that can be used to access elements by passing element numbers.

Example:

var str0 = strList[0];

The List <T> class also provides the foreach () method, which returns void and the parameter is Action. The ForEach () method traverses each item in the set and calls the method passed as a parameter for each item.

Example:

List<string> strList = new List<string>();strList.Add("zhangsan");strList.AddRange(new string[] { "lisi", "wangmazi" });strList.AddRange(new List<string> { "zhaoliu", "qianqi" });strList.ForEach(Console.WriteLine);Console.ReadKey();

Run the above Code and the result is as follows:

 

Pass the Console. WriteLine () method as a parameter to the ForEach () method.

 

(5) delete an element

When deleting an element, you can use the index or the element to be deleted.

Example:

strList.RemoveAt(1);

Deleting by index is faster.

The RemoveRange () method can delete many elements from a collection.

strList.RemoveRange(0, 1);

You can also use the RemoveAll () method to delete all specified elements, or the Clear () method defined by the ICollection <T> interface.

 

(6) Search

You can use IndexOf (), LastIndexOf (), FindIndex (), FindLastIndex (), Find (), FindLast (). If you only check whether the element Exists, the List <T> class provides the Exists () method.

Example:

int index = strList.IndexOf("lisi");

 

(7) sorting

The List <T> class can use the Sort () method to Sort elements. The Sort () method uses a fast Sorting Algorithm to compare all elements, and the value ends until the entire list is sorted.

 

(8) type conversion

Use the ConvertAll <TOutput> () method of the List <T> class to convert all types of sets to another type.

Example:

List<object> objList = strList.ConvertAll<object>(s => s);

 

 

2. Read-only set

The AsReadOnly () method in the List <T> set returns the ReadOnlyCollection <T> type object.

 

 

(3) queue

A Queue <T> is a set of FIFO methods. The queue can only add an element to the queue. This element is placed at the end of the queue (Enqueue () method) to obtain the element from the queue header (using the Dequeue () method ).

Example:

Queue<string> qu = new Queue<string>();qu.Enqueue("zhangsan");qu.Enqueue("lisi");qu.Enqueue("wangmazi");var dqu = qu.Dequeue();Console.WriteLine(dqu);

Run the above Code and the result is as follows:

 

It should be noted that the Dequeue () method will delete the element from the queue after obtaining the element. The Peek () method will only be used to obtain and not delete the element. Using the enumerator does not change the element status. Because the Queue <T> class does not implement the IList <T> interface, you cannot use the indexer to access the Queue.

 

 

(4) Stack

The Stack (<T>) is similar to the Queue (Queue <T>), but the elements added to the Stack are read first. Stack is a post-import, first-out (LIFO) container. The stack uses the Push () method to add elements and the Pop () method to obtain the most recent elements.

Example:

Stack<string> st = new Stack<string>();st.Push("zhangsan");st.Push("lisi");st.Push("wangmazi");var pst = st.Pop();Console.WriteLine(pst);

Run the above Code and the result is as follows:

 

It should be noted that the Pop () method will delete the element from the queue after obtaining the element, and the Peek () method will only get and not delete the element. Using the enumerator does not change the element status.

 

 

(5) linked list

The linked list <T> is a two-way linked list. Its elements point to the elements before and after it. The advantage of a linked list is that the inserted list is very fast in the middle. The disadvantage is that only one access is allowed. A linked list cannot store only values in the list. It also contains the information of the previous and next elements.

Member List <T> class-defined members can access the First and Last elements (First and Last) in the linked list, insert elements (AddAfter (), AddBefore () at the specified position (), AddFirst () and AddLast () methods), delete the specified location element (Remove (), RemoveFirst () and RemoveLast () methods), and start from the Linked List (Find () method) or the FindLast () method starts to search for elements.

Example:

Vertex list <int> list = new vertex list <int> (); list. addFirst (2); list. addFirst (1); list. addLast (5); list. addLast (6); list. addAfter (list. find (2), 3); list. addBefore (list. find (5), 4); foreach (var item in list) {Console. writeLine (item);} list. removeLast (); Console. writeLine ("after removing the end element:"); foreach (var item in list) {Console. writeLine (item );}

Run the above Code and the result is as follows:

 

 

 

(6) ordered list

If you need to sort the required set based on the key pair, you can use the SortedList <TKey, TValue> class. This class sorts the elements by key.

Example:

SortedList <string, string> list = new SortedList <string, string> (); list. add ("B", "lisi"); list. add ("a", "zhangsan"); list. add ("c", "wangmazi"); foreach (var item in list) {Console. writeLine ("sorting position {0}, is {1}", item. key, item. value );}

Run the above Code and the result is as follows:

 

 

 

(7) Dictionary

The dictionary is also a ing or scattering list. The main feature of the dictionary is to quickly search for values based on keys. You can also add and delete elements freely, which is a bit like the List <T> class, but there is no performance overhead for moving subsequent elements in the memory.

 

1. Key type

The key used as the dictionary must override the GetHashCode () method of the Object class, implement the IEquatable <T>. Equals () method, or override the Equals () method of the Object class. You can also implement the GetHashCode () method and Equals () method of the IEqualityComparer <T> interface.

Note that if the. Equals (B) method returns true, the. GetHashCode () and B. GetHashCode () methods must always return the same hash code.

Strings are more suitable for use as keys than Int32.

 

2. dictionary example

Dictionary<string, string> dic = new Dictionary<string, string>();dic.Add("a", "zhang");dic.Add("b", "li");dic.Add("c", "wang");foreach (var item in dic){    Console.WriteLine(item);}

 

3. Lookup class

The Lookup <TKey, TElement> class is very similar to the Dictionary <TKey, TValue> class, but maps the key to a value set. The Lookup <TKey, TValue> class cannot be created as a general dictionary, but must call the ToLookup () method. This method returns a Lookup <TKey, TElement> object. To call the ToLookup () method, you must pass a Func <TSource, TKey> type delegate to define the key selector.

Example:

var personList = new List<Person>();personList.Add(new Person() { Name = "zhangsan", Age = 13 });personList.Add(new Person() { Name = "lisi", Age = 15 });personList.Add(new Person() { Name = "wangmazi", Age = 13 });personList.Add(new Person() { Name = "zhaoliu", Age = 18 });var personLookup = personList.ToLookup(p => p.Age);foreach (var item in personLookup[13]){    Console.WriteLine(item.Name);}

 

4. Ordered dictionary

The SortedDictionary <TKey, TValue> class is a binary search tree in which elements are sorted by keys. This key type must implement the IComparable <TKey> interface. If not, you can pass a comparator that implements the IComparer <TKey> interface.

  • The SortedList <TKey, TValue> class uses less memory than the SortedDictionary <TKey, TValue> class.
  • SortedDictionary <TKey, TValue> class inserts and deletes elements quickly.
  • When you fill a set with sorted data, SortedList <TKey, TValue> classes are faster if you do not need to modify the capacity.

 

 

(8) Set

Contains non-repeated sets and becomes "set )".. NET Framework contains two sets (HashSet <T> and SortedSet <T>), both of which implement the ISet <T> interface. The HashSet <T> set contains an unordered list of non-repeated elements, and the SortedSet <T> contains a non-repeated ordered list.

Example:

1 var firstNameSet1 = new HashSet <string> (); 2 firstNameSet1.Add ("zhang"); 3 firstNameSet1.Add ("zhang"); 4 firstNameSet1.Add ("li "); 5 firstNameSet1.Add ("wang"); 6 firstNameSet1.Add ("zhao"); 7 foreach (var item in firstNameSet1) 8 {9 Console. writeLine (item); 10} 11 var firstNameSet2 = new HashSet <string> (); 12 firstNameSet2.Add ("Smith"); 13 firstNameSet2.Add ("Johnson "); 14 firstNameSet2.Add ("Williams"); 15 firstNameSet2.Add ("Jones"); 16 var firstNameSet = new SortedSet <string> (); 17 firstNameSet. unionWith (firstNameSet1); 18 firstNameSet. unionWith (firstNameSet2); 19 Console. writeLine ("bringing two unordered sets to the ordered set:"); 20 foreach (var item in firstNameSet) 21 {22 Console. writeLine (item); 23}

Run the above Code and the result is as follows:

 

 

 

(9) observed Sets

If you want to delete or add elements in the set, you can use the ObservableCollection <T> class.

Example:

1 static void Main (string [] args) 2 {3 ObservableCollection <string> obs = new ObservableCollection <string> (); 4 obs. collectionChanged + = Obs_changeInfo; 5 obs. add ("1"); 6 obs. add ("2"); 7 Console. readKey (); 8} 9 10 11 private static void Obs_changeInfo (object sender, yycollectionchangedeventargs e) 12 {13 Console. writeLine ("trigger event operation method: {0}", e. action); 14 var targetElement = e. newItems = null? E. OldItems: e. NewItems; 15 foreach (var item in targetElement) 16 {17 Console. WriteLine ("trigger element: {0}", item); 18} 19}

Run the above Code and the result is as follows:

 

 

 

(10) array

If the number to be processed has many bits, you can use the BitArray class and BitVector32 structure. (I have no idea what this will do. I will not take notes for the moment)

 

 

(11) unchanged set

If an object can change its state, it is difficult to use it in multiple simultaneously running tasks. First fill in the set, and then change it to an unchanged array will be more efficient. A variable set can be used again when some processing is required. In this case, you can use the builder class provided by the unchanged set.

Example:

List <string> list = new List <string> (); list. add ("zhang"); list. add ("li"); var immutableList = list. toImmutableList (); // The variable set is converted to the variable set var immutableListBuilder = immutableList. toBuilder (); // reconvert to a variable set immutableListBuilder. add ("wang"); immutableList = immutableListBuilder. toImmutable (); // The variable set is converted into the unchanged set foreach (var item in immutableList) {Console. writeLine (item );}

Run the above Code and the result is as follows:

 

The read-only set provides read-only attempts to the set. The set can still be modified without using read-only attempts to access the set. The unchanged set cannot be modified.

 

 

(12) Concurrent set

Starting from. NET 4, The namespace System. Collections. Concurrent in. NET provides several thread-safe collection classes. The IProducerConsumerCollection interface is defined for thread-safe access to the collection. The most important methods in this interface are the TryAdd () method and the TryTake () method.

Concurrency set reference: http://blog.csdn.net/wangzhiyu1980/article/details/45497907

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.