C # Collection Summary

Source: Internet
Author: User
Tags wrapper



Let's take a look at the basic information of the following collection

1. The collection types in FCL are divided into generic sets and Non-generic collections.

2. Classes and interfaces for Non-generic collections are located in the System.Collections namespace.

3. Classes and interfaces for generic collections are located in the System.Collections.Generic namespace.

The ICollection interface is the base interface of the Non-generic collection class in the System.Collections namespace, it inherits from the IEnumerable interface, and inheriting from the IEnumerable interface means that implementing the implementation class of the interface needs to implement an enumerator method: GetEnumerator, the method returns data of type IEnumerator. The IDictionary and IList interfaces inherit from ICollection as a more specialized interface in which the IDictionary interface is a key/value pair interface, and its implementation is such as the Hashtable class; IList is a collection of values, and its members are accessible through the index. such as the ArrayList class, the secondary class set and the array can be considered as a variable set, the advantages are, the length of automatic growth. Ienumerable<t> and IEnumerable are the base interfaces for all collections or collection interfaces, and all collection interfaces or collections inherit and implement it. Where IEnumerable is the lowest-level interface. The System.Object type is stored in a Non-generic collection.

The interfaces for non-generic and generic collections are listed below

Non-generic collection Interface generic Collection interface description

ICollection icollection<t> defines the size (Count) of all collections, the enumerator (foreach), and the Synchronization (CopyTo) method, inherited from IEnumerable

IList ilist<t> represents a set of objects that can be accessed individually by index (like an array)

IDictionary Idictionary<t> represents a collection of key/value pairs

IComparer Icomparer<t> defines a method that is implemented by comparing two objects

IEqualityComparer iequalitycomparer<t> defines methods to support equality comparisons of objects

IEnumerable ienumerable<t> exposes the enumerator. Implementing this interface means allowing a foreach statement to iterate through the elements in the collection

IEnumerator Ienumerator<t> supports simple iterations on a generic collection

The following is a detailed description of the various collection interfaces and collections. Personally, I think we should start with the foundation.

With the MSDN IEnumerable first, the extension method is not said, the extension method skipped, left to learn LINQ time to say.

1, IEnumerable interface on a method, no attributes.

Method description

GetEnumerator Returns an enumerator that iterates through the collection. Implements or inherits the interface, just for this method, which can be traversed by foreach.

2, ienumerable<t> interface is the same, is also a method, no attributes.

Method description

GetEnumerator Returns an enumerator that iterates through the collection.

3, ICollection Interface

Method description

CopyTo starts at a specific array index and copies ICollection elements into an array.
GetEnumerator Returns an enumerator that iterates through the collection. (inherited from IEnumerable.) )

Property

Count gets the number of elements contained in the ICollection. The source of the original count is here.
IsSynchronized gets a value that indicates whether access to ICollection (thread-safe) is synchronized.
SyncRoot gets the objects that can be used to synchronize ICollection access.

4, Icollection<t>

Method description

Count gets the number of elements contained in icollection< (of < (t>) >).
IsReadOnly gets a value that indicates whether icollection< (of < (t>) >) is read-only.

Property

Add adds an item to the icollection< (of < (t>) >).
Clear removes all items from the icollection< (of < (t>) >).
Contains determines whether icollection< (of < (t>) >) contains a specific value.
CopyTo copies the elements of icollection< (of < (t>) >) to an array, starting with a specific array index.
GetEnumerator has been overloaded.
Remove removes the first occurrence of a particular object from the icollection< (of < (t>) >).

This icollect<t>, only to start a little set of shadows, can add, clear, no wonder it as a generic collection interface base class.

5, IList

IList inherited ICollection and IEnumerable.

Method description

Add adds an item to the IList.
Clear removes all items from the IList.
Contains Determines whether IList contains a specific value.
CopyTo starts at a specific array index and copies ICollection elements into an array. (inherited from ICollection.) )
GetEnumerator Returns an enumerator that iterates through the collection. (inherited from IEnumerable.) )
IndexOf determines the index of a particular item in the IList.
Inserts an item into the IList at the specified index.
Remove removes the first occurrence of a particular object from the IList.
RemoveAt removes the IList item at the specified index.

Property

Count gets the number of elements contained in the ICollection. (inherited from ICollection.) )
Isfixedsize gets a value that indicates whether the IList has a fixed size.
IsReadOnly gets a value that indicates whether the IList is read-only.
IsSynchronized gets a value that indicates whether access to ICollection (thread-safe) is synchronized. (inherited from ICollection.) )
Item Gets or sets the element at the specified index.
SyncRoot gets the objects that can be used to synchronize ICollection access. (inherited from ICollection.) )

As you can see, in the continuous inheritance process, these interfaces constantly add their own things, more inheritance, more inheritance.

6, Ilist<t>

Ilist<t> inherited icollection<t>,ienumerable<t>,ienumerable.

Method description

Add adds an item to the icollection< (of < (t>) >). (Inherited from icollection< < (t>) >). )
Clear removes all items from the icollection< (of < (t>) >). (Inherited from icollection< < (t>) >). )
Contains determines whether icollection< (of < (t>) >) contains a specific value. (Inherited from icollection< < (t>) >). )
CopyTo copies the elements of icollection< (of < (t>) >) to an array, starting with a specific array index. (Inherited from icollection< < (t>) >). )
GetEnumerator has been overloaded.
IndexOf determines the index of a specific item in ilist< (of < (t>) >).
Inserts an item into the ilist< (t>) >) at the specified index.
Remove removes the first occurrence of a particular object from the icollection< (of < (t>) >). (Inherited from icollection< < (t>) >). )
RemoveAt removes the ilist< (of < (t>) >) item at the specified index.

Property

Count gets the number of elements contained in icollection< (of < (t>) >). (Inherited from icollection< < (t>) >). )
IsReadOnly gets a value that indicates whether icollection< (of < (t>) >) is read-only. (Inherited from icollection< < (t>) >). )
Item Gets or sets the element at the specified index.

Similarly, in the continuous succession, the addition of new things, more and more powerful functions, support index access and settings is ilist<t> this source. Have been confused, why NHibernate chose this interface to return the data, in fact, the interface of the things enough.

7, Idictionary<tkey,tvalue> interface

Idictionary<tkey,tvalue> is a set of key/value pairs that appear at the bottom of the list, equivalent to icollection<t> in a set of values

Method description

ADD has been overloaded.
Clear removes all items from the icollection< (of < (t>) >). (Inherited from icollection< < (t>) >). )
Contains determines whether icollection< (of < (t>) >) contains a specific value. (Inherited from icollection< < (t>) >). )
ContainsKey determines whether idictionary< (of < (TKey, tvalue>) >) contains an element with the specified key.
CopyTo copies the elements of icollection< (of < (t>) >) to an array, starting with a specific array index. (Inherited from icollection< < (t>) >). )
GetEnumerator has been overloaded.
Remove is overloaded.
TryGetValue gets the value associated with the specified key.

Property

Count gets the number of elements contained in icollection< (of < (t>) >). (Inherited from icollection< < (t>) >). )
IsReadOnly gets a value that indicates whether icollection< (of < (t>) >) is read-only. (Inherited from icollection< < (t>) >). )
Item Gets or sets the element with the specified key.
The keys get icollection< (of < (t>) >) that contains the keys for idictionary< (of < (TKey, tvalue>) >).
Values gets the icollection< (of < (t>) >) that contains the values in idictionary< (of < (TKey, tvalue>) >).

The interface provides the same functionality as icollection<t>, which is actually the open Zong Lipai of the key/value pair.

8, IDictionary

Method description

Add adds an element with the supplied key and value to the IDictionary object.
Clear removes all elements from the IDictionary object.
Contains determines whether the IDictionary object contains an element with the specified key.
CopyTo starts at a specific array index and copies ICollection elements into an array. (inherited from ICollection.) )
GetEnumerator has been overloaded.
Remove removes the element with the specified key from the IDictionary object.

Property

Count gets the number of elements contained in the ICollection. (inherited from ICollection.) )
Isfixedsize gets a value that indicates whether the IDictionary object has a fixed size.
IsReadOnly gets a value that indicates whether the IDictionary object is read-only.
IsSynchronized gets a value that indicates whether access to ICollection (thread-safe) is synchronized. (inherited from ICollection.) )
Item Gets or sets the element with the specified key.
The keys gets the ICollection object, which contains the keys of the IDictionary object.
SyncRoot gets the objects that can be used to synchronize ICollection access. (inherited from ICollection.) )
Values gets the ICollection object, which contains the values in the IDictionary object.

9, Iset<t>

Iset<t> is also inherited from Icollection<t>,ienumerable<t>,ienumerable

Method description

Add (T) adds an item to the icollection<t>. (inherited from Icollection<t>.) )
Add (T) adds an element to the current set and returns a value indicating whether the element was successfully added.
Clear removes all items from the icollection<t>. (inherited from Icollection<t>.) )
Contains Determines whether icollection<t> contains a specific value. (inherited from Icollection<t>.) )
CopyTo starts with a specific array index and copies icollection<t> elements into an array. (inherited from Icollection<t>.) )
Exceptwith removes all elements from the specified collection from the current set.
GetEnumerator () returns an enumerator that iterates through the collection. (inherited from IEnumerable.) )
GetEnumerator () returns an enumerator that iterates through the collection. (inherited from Ienumerable<t>.) )
Intersectwith modifies the current set so that it contains only elements that also exist in the specified collection.
Ispropersubsetof determines whether the current setting is correct (strictly) specifies a subset of the collection.
IsProperSupersetOf determines whether the current setting is correct (strictly) specifies the superset of the collection.
IsSubsetOf determines whether a set is a subset of the specified collection.
Issupersetof determines whether the current set is a superset of the specified collection.
Overlaps determines whether the current set overlaps the specified collection.
Remove removes the first occurrence of a particular object from the icollection<t>. (inherited from Icollection<t>.) )
Setequals determines whether the current set contains the same elements as the specified collection.
Symmetricexceptwith modifies the current set so that it contains only the current set or elements that exist in the specified collection (but not the elements that are common to both).
Unionwith modifies the current setting so that it contains all the elements in the current set or in the specified collection.

Remembering the relationships between these interfaces is really important, and the methods and attributes are irrelevant, but you need to remember the features you provide and the inheritance relationships.

First of all, IComparer interface, this interface is a method for how to compare two objects

    public class stringlengthcomparer:icomparer<string>
    {public
        int Compare (string s1, string s2)
        {
            if (S1. Length > S2. Length)
            {return
                (1);
            }
            else if (S1. Length < S2. Length)
            {return
                (2);
            }
            else
            {return
                (0);
            }
        }
    }

Now that we've finished with the set interface, let's start with the collection.

1, ArrayList

ArrayList implements the IList, ICollection, IEnumerable interface.

ArrayList is very similar to the name of array, now to compare the similarities and differences between the two.

Same point:

(1), both realize the IList, ICollection, IEnumerable interface.

(2), both can use an integer index to access elements in the collection, including reading and assignment, and the index in the collection starts with 0.

Different points:

(1), ArrayList is a collection, and the array is arrays.

(2), ArrayList is a specific class, array is an abstract class.

(3), the array must specify the number of elements in the instantiation, once the quantity is determined, it cannot be changed, and ArrayList expands this, when instantiating a ArrayList instance, you can not specify the number of collection elements (with default initial capacity), of course you can also specify the initial capacity.

(4), the length property is used when getting the number of elements of the array, and the Count property is used to get the number of elements of the ArrayList collection.

(5), the array can have multidimensional, and ArrayList can only be one-dimensional.

To see what ArrayList specifically offers.

Attribute description

Capacity Gets or sets the number of elements that ArrayList can contain.
Count gets the number of elements actually contained in the ArrayList.
Isfixedsize gets a value that indicates whether the ArrayList has a fixed size.
IsReadOnly gets a value that indicates whether the ArrayList is read-only.
IsSynchronized gets a value that indicates whether access to ArrayList (thread-safe) is synchronized.
Item Gets or sets the element at the specified index.
SyncRoot gets the objects that can be used to synchronize ArrayList access.

Method

Adapter creates a ArrayList wrapper for a particular IList.
Add adds an object to the end of the ArrayList.
AddRange adds ICollection elements to the end of the ArrayList.
BinarySearch has been overloaded. Finds a specific element in a sorted ArrayList or part of it using a pair-indexing algorithm.
Clear removes all elements from the ArrayList.
Clone creates a ArrayList copy of the shallow table.
Contains determines whether an element is in ArrayList.
CopyTo has been overloaded. Copies a ArrayList or part of it to a one-dimensional array.
Fixedsize has been overloaded. Returns a fixed-size list wrapper with elements that allow modification but are not allowed to be added or removed.
GetEnumerator has been overloaded. Returns an enumerator that iterates through the ArrayList.
GetRange returns ArrayList, which represents a subset of the elements in the source ArrayList.
IndexOf has been overloaded. Returns the zero-based index of the first occurrence of a value in a ArrayList or part of it.
Insert inserts an element into the ArrayList at the specified index. can be inserted at any location.
Insertrange inserts an element from the collection into the ArrayList at the specified index.
LastIndexOf has been overloaded. Returns the zero-based index of the last occurrence of a value in a ArrayList or part of it.
ReadOnly has been overloaded. Returns a read-only list wrapper.
Remove removes the first occurrence of a particular object from the ArrayList.
RemoveAt removes the element at the specified index of the ArrayList.
RemoveRange removes a certain range of elements from the ArrayList.
Repeat returns ArrayList, whose element is a copy of the specified value.
Reverse has been overloaded. Reverses the order of elements in a ArrayList or part of it.
SetRange copies the elements of the collection to a range of elements in the ArrayList.
Sort has been overloaded. Sorts the elements in a ArrayList or part of it.
Synchronized has been overloaded. Returns a synchronized (thread-safe) List wrapper.
ToArray has been overloaded. Copies the ArrayList elements to the new array.
TrimToSize sets the capacity to the actual number of elements in ArrayList.

        static void Main (string[] args) {ArrayList ArrayList = new ArrayList ();                       Arraylist.add (1);
            Add method, adding an element to the arrayList arraylist.add ("Hello");
            Arraylist.add (3.265);
            IList IList = arrayList;
            ICollection icollection = iList;  IEnumerable IEnumerable = ICollection; Embodies the ArrayList inheritance relationship foreach (object obj in iEnumerable) {Console.WriteLine (obj.
            ToString ());  BOOL B = arraylist.contains ("Hello");                 Determine if the ArrayList contains an element Console.WriteLine (b);
            Output True object[] Objarr = new Object[arraylist.count + 1];
            Objarr[0] = "I am used to occupy the place"; Arraylist.copyto (Objarr, 1); A cheap one, that is, accept that the array starts at 1, and the default is 0 foreach (object obj in Objarr) {Console.Write (obj).    ToString () + "-"); Output I was used to occupy the bit of the -3.265-} Console.writEline ();  ArrayList AL = arraylist.fixedsize (ArrayList); The static method returns a Fixed-size ArrayList object, and the number is not allowed to change.
            That is, it cannot be added or deleted. Console.WriteLine (AL.  Isfixedsize); The output is true//al. ADD (111);
            The exception is reported here, "the size of the set is fixed" ArrayList alreadonly = arraylist.readonly (ArrayList);   Console.WriteLine (alreadonly.isreadonly);   Output true ArrayList AL1 = Arraylist.getrange (1, 2); The subset foreach (Object obj in AL1) {Console.Write (obj) is intercepted in indexed order.  ToString ());

            Output Hello 3.265 The new ArrayList that can be intercepted contain only 1, 2-bit} Console.WriteLine ();   int indexlocation = Arraylist.indexof (1);   Retrieves from the left, returns the order of the first matching element Console.WriteLine (indexlocation);       Output 0 Arraylist.add (1);
            In order to reflect the difference of lastindexof, first add a 1 int lastlocation = Arraylist.lastindexof (1);    Console.WriteLine (lastlocation);  Returns 3 Arraylist.insert (2, "Insert inserted element"); The difference between this method and add is that it can be plugged in anywhereinto foreach (Object obj in arrayList) {Console.Write (obj.    ToString () + "");
            Output 1 Hello Insert inserted element 3.265 1} ArrayList arr = new ArrayList (); Arr.
            ADD (1); Arr.
            ADD (2);
            Arraylist.addrange (arr); foreach (Object obj in arrayList) {Console.Write (obj.    ToString () + "-");
            Output 1 Hello Insert elements 3.265 1 1 2 You can see that a new collection is appended to the last} arraylist.remove (2); foreach (Object obj in arrayList) {Console.Write (obj.    ToString () + "-");

            Output 1 Hello Insert inserted element 3.265 1 1 can see 2 has been removed} Console.WriteLine ();
            Arraylist.removeat (0); foreach (Object obj in arrayList) {Console.Write (obj.    ToString () + "-");

            Output Hello Insert inserted element 3.265 1 1 You can see the No. 0 element "2" has been removed} Console.WriteLine ();
 Arraylist.reverse ();           foreach (Object obj in arrayList)//{//Console.Write (obj.        ToString () + "-");
            All elements of output order reversal//} ArrayList AL3 = new ArrayList ();      Arraylist.setrange (0,AL3); From the No. 0 bit, copy the element into AL3 (object obj in AL3) {Console.Write (obj).    ToString () + "-");
            Output Hello Insert inserted element 3.265 1 1} object[] Objarrs = new Object[arraylist.count];
            Objarrs = Arraylist.toarray (); foreach (Object obj in Objarrs) {Console.Write (obj.
            ToString () + "-");

            } Console.WriteLine ();     arraylist.capacity = 5;
            Reads or sets the number of elements that can be included, if less than the current error.     Console.WriteLine (Arraylist.count);
            Output 5 arraylist.trimtosize ();     Console.WriteLine (Arraylist.count);
        Output 5 console.readkey (); }

2. Non-generic collection hashtable

Hashtable implements the IDictionary, ICollection, and IEnumerable interfaces. Note that the hashtable,t is lowercase. Because it is a non-generic collection, all that is stored in is type object, whether it is a key or a value.

The main points of Hashtable.

(1), Hashtable only non-generic version.

(2) The keys in the Hashtable class do not allow duplicates, but the values are OK.

(3), the Hashtable class is stored in a key-value pair, the value can be null, but the key is not allowed to be null.

(4), Hashtable does not allow sorting operations.

Here's an example, Hashtable provides a function that is similar to arrarylist, except that it stores key-value pairs. Just write a basic short sample.

        static void Main (string[] args)
        {
            Hashtable ht = new Hashtable ();
            Ht. ADD (1,1);
            Ht. ADD ("I Love You", "Yes.") ");
            Console.WriteLine (HT. Count);    Output 2
            Console.WriteLine (ht["I love You");   Output "Is it. "  Gets the value Console.WriteLine (HT) with the key
            . Contains (1));  Output true

            console.readkey ();
        }

3. Queue and Queue<t>

Queue becomes a queue, which is a data structure that is inserted at one end of the list and is removed from the other end of the list. It's like a one-way street, only from a passage, from one end. The queue class implements the ICollection and IEnumerable interfaces.

Some important features of the queue.

1, advanced first Out

2, you can add null values to the collection

3, allow the elements in the collection to repeat

4, the queue capacity will be automatically added on demand

5. The queue's equal factor is the number that is multiplied by the current capacity when larger capacity is required, and the default is 2.0.

Now list the capabilities of the queue one feature

Member Type description

The Clear method removes all objects from the queue, emptying the queues.

The Contains method determines whether an element is in the queue

The Enqueue method adds an object to the end of the queue row

The Dequeue method removes and returns the object at the beginning of the queue.

The Peek method returns the object at the start of the queue but does not remove it, unlike the column, the column is removed

Provides a similar function, now gives an example, mainly shows the role of the queue.

 static void Main (string[] args) {Queue q = new Queue ();
            Q.enqueue (1);
            Q.enqueue ("Homesick!"); Q.enqueue (1.23); 
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.