C # Advanced Programming (9th Edition) Chapter 10th collection Notes

Source: Internet
Author: User

Though I've hit a lot of code, I've never ducked to look at other languages except C + +.

Today look at the src,c# of the company's old project, the usage of linq+dictionary. So find the data of C # to learn a bit, the mother of the weather.

In the future can not be used in C + + writing ideas, to live.

------------------------------------------------------------------I'm a split line---------------------------------------- -------------------------------

The following study notes

List list<t>, queues, stacks, linked lists, dictionaries, and sets; bit arrays and concurrent collections "Multithreaded environment use"set of excuses and typesMost collection classes are in the System.Collections and System.Collections.Generic namespaces. Generic collection ==> System.Collections.Generic specialized for a particular type of collection class ==> System.Collections.Concurrent immutable Collection class ==> System.Collections.ImmutableListThe. NET Framework provides generic class list<t> for dynamic lists. This class implements the IList, ICollection, IEnumerable, ilist<t>, icollection<t>, and ienumerable<t> interfaces. ArrayList is a non-generic list that can use any object type as its element. Create an empty list using the default constructor. When an element is added to a list, the capacity of the list expands to accommodate 4 elements. If you add a 5th element, the size of the list is set to a new setting of 8 elements, and if 8 elements are not enough, the size of the list is reset to include 16 elements. The capacity of the list is reset to twice times the original each time. If the contents of the list change, the entire collection will be reassigned to a new block of memory. That is, create a new array, which is twice times the size of the original. Creates a list of the specified number of elements
list<int> intlist = new list<int> (10);
Collection classes that can be accessed through an index have the ArrayList, StringCollection, and List<t> ForEach () methods to traverse each item in the collection, calling the method passed as a parameter of each item.
public delegate void action<t> (T obj);p ublic void Actionhandler (Racer obj); racers. ForEach (Console.WriteLine); Racers. ForEach (R = Console.WriteLine ("{0:a}", r);//LAMBDA expression

Delete ElementWhen you delete an element, you can either take advantage of the index or pass the element you want to delete. Deleting by index is faster because you must search the collection for the element that you want to delete. The Remove () method now searches the collection, using the IndexOf () method to get the index of the element, using the index to delete the element. The IndexOf () method first checks whether the element type implements the Iequatable<t> interface. If you are calling the Equals () method of this interface, determine whether the elements in the collection are equal to the elements passed to the Equals () method. If this interface is not implemented, the Equals () method of the object class is used to compare these elements. The default implementation code of the Equals () method in the object class compares a value type to a reference type by only comparing its references. Override the Iequatable<t> interface or the Object.Equals () method to delete a list element based on a specific property of the list element object.The 7th chapter describes how to override the Equals () methodSearchThere are different ways to search for elements in a collection. You can get a reference to the element you are looking for, or search the element itself. Methods are:
IndexOf () LastIndexOf () FindIndex () FindLastIndex () Find () FindLast () checks whether the element exists: List<t>. Exists () method;
IndexOf () can specify that you do not need to search the entire collection, you need to specify the starting index and the number of elements that need to be iterated findindex () to search for elements that have an attribute public int findindex (predicate<t> match); The predicate<t> type is a delegate that returns a bool value int index = racers. FindIndex (r = R.country = = "Finland"); The FindIndex () method returns the index of the element being looked up. The Find () method can also directly get the elements in the collection, in addition to getting the index. Racer Racer = racers. Find (r = R.firstname = = "Niki"); To obtain all items that match the predicate<t> type, instead of one, you can use the FindAll () method;SortThe List<t> class can use the sort () method to sort elements. The Sort () method uses thefast sorting algorithm. The Sort () method uses several overloaded methods:
public void list<t>. Sort ();p ublic void List<t>. Sort (comparison<t>);p ublic void List<t>. Sort (icomparer<t>);p ublic void List<t>. Sort (Int32, Int32, icomparet<t>);

1. Only the elements in the collection implement the IComparable interface to use the sort () method without parameters;

2. If you need to sort by an element type that is not supported by default, you should use other techniques, such as passing an object that implements the Icomparer<t> interface. 3. Another way to sort by using the overloaded sort () method. Call the reverse () method to reverse the order of the entire collection.Type ConversionsUsing the Convertall<toutput> () method of the List<t> class, you can convert a collection of all types to another type. The Convertall<toutput> () method uses a Converter delegate: public sealed delegate TOutput Converter<tinput, toutput> (tinput from);
eg:list<person> persons = Racers. Convertall<person> (r = new Person (r.firstname + "" + R.lastname));

read-only collectionThe AsReadOnly () method of the List<t> collection returns an object of type readonlycollection<t>. The Readonlycollection<t> class implements the same interface as the List<t> collection, but if the modification throws an exception NotSupportedException exception. The readonlycollection<t> also implements the ireadonlycollection<t> and ireadonlylist<t> interfaces.QueueThe Queue<t> namespace System.Collections.Generic queue is a collection of its elements that are processed in first-out (FIFO) fashion. Multiple queues can be used, and one queue corresponds to one priority. This is true for print queues and thread queues. An array can be created for a set of queues, and an entry in the array represents a priority. The internal Queue<t> class uses an array of type T, which implements the ICollection and Ienumerable<t> interfaces. The element cannot be accessed with an indexer because the Ilist<t> interface is not implemented. The Queue<t> method is as follows:
Countenqueuedequeuepeek//Read an element from the head of the queue without deleting it trimexcess//Reset the capacity of the queue, the Dequeue () method removes the element from the queue but does not reset the queue capacity to remove empty elements from the head of the queue, The TrimExcess () method should be used

Multithreading can be accessed at the same time, but locks the queue's access with the lock statement:

public class Documentmanager {private readonly queue<document> documentqueue = new queue<document> (); void Adddocument (document DOC) {lock (this) {Documentqueue.enqueue (DOC)}} public Document GetDocument () {Document DOC = n Ull;lock (this) {doc = Documentqueue.dequeue ();} return doc;} public bool Isdocumentavailable {get {return documentqueue.count > 0;}}}

StackThe stack is a last-in, first-out (LIFO) container that implements the ienumerable<t> and ICollection interfaces with the same,stack<t> class as the Queue<t> class. Member List:
Countpushpoppeekcontains

In the Foreach method, all elements are iterated using the IEnumerable interface, and the stack's enumerator does not delete the element, it simply returns the element individuallyLinked listLinkedlist<t> is a matter of a two-way chain table, and if you insert an element into the middle of the list, you can use the linked table very quickly. When inserting an element, you only need to modify the next reference of the previous element and the previous reference of the next element so that they refer to the inserted element.in the List<t> class, when you insert an element, you need to move all the elements that follow the element. The disadvantage of a linked list: The elements of the list can only be accessed one by one, which takes a long time to find the elements that are in the linked list or the tail.list with sequenceIf you need to sort the desired collection based on the key, you can use the Sortlist<tkey, Tvalue> class. This class sorts the elements by key.DictionaryThe. NET Framework provides several dictionary classes, the most important class that can be used is Dictionary<tkey, tvalue>type of keyThe type used as the key in the dictionary must override the GetHashCode () method of the object class, and the performance of the dictionary depends on the implementation code of the GetHashCode () method. In addition to implementing the GetHashCode () method, the key type must also implement IEQUATABLE&LT;T&GT;. Equals () method, or override the Equals () method of the object class.Lookup classLookup<tkey, telement> maps a key to a set of values, Lookup<tkey, Telement> class is implemented in assembly System.core, with the System.Linq namespace. Lookup<tkey, the Telement> class cannot be created as a generic dictionary, but must call the ToLookup () method, which returns a Lookup<tkey, Telement> object. The ToLookup () method is an extension method that can be used to implement all classes of the Ienumerable<t> interface.ordered DictionariesSorteddictionary<tkey, the Tvalue> class is a binary search tree in which the elements are sorted by key. The key type must implement the Icomparable<tkey> interface. If the type of the key cannot be sorted, you can also create a comparer that implements the Icomparer<tkey> interface, using the comparer as a parameter to the constructor of an ordered dictionary.Set。。。。 Not to be continued

C # Advanced Programming (9th Edition) Chapter 10th collection Notes

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.