C # container classes, interfaces, performance details

Source: Internet
Author: User
Tags shallow copy sorts

1 Indexer

[] The declared variable must be fixed-length, that is, the length is static; object[] Objectarray = new OBJECT[10];
Objectarray is a shallow copy , which assigns an address value only in memory, at which time each item is a null reference;

  Application examples

     adjustablepanel[] adjustpanelarrays = new ADJUSTABLEPANEL[12];          foreach (Control ultracontrol in). Controls)            {                if (ultracontrol.gettype () = = typeof (Ultragrid) | |                 Ultracontrol.gettype () = = typeof (Ultrachart) | |   Ultracontrol.gettype () = = typeof (Panel))                {                //adjustpanelarrays[index] is now null, so a null reference bug                    appears Adjustpanelarrays[index]. Controls.Add (Ultracontrol);                 }            }

2 Array

Provides methods for creating , manipulating , searching , and sorting arrays, and thus serves as the base class for all arrays in the common language runtime. The length is fixed and cannot be dynamically incremented on demand ; Thearray is an abstract class and cannot be created with the new array ; GetValue returns the object type.

            Array MyArray = array.createinstance (typeof (int), 3);            Myarray.setvalue (1,0);            Myarray.setvalue (2,1);            Myarray.setvalue (3,2);            GetValue returns an object type that needs to be type promoted to int            int val2 = (int) myarray.getvalue (2);

3 ArrayList

The IList interface is implemented using an array of sizes that can be dynamically incremented on demand, and is for any type.

            ArrayList al = new ArrayList ();            ArrayList ArrayList = new ArrayList ();            Al. ADD ("Qaz");            Al. ADD (1);            Al. ADD (New list<object> ());                        String str = (string) al[0];                        int intval = (int) al[1];            List<object> Objs = (list<object>) al[2];

Summarize
  [], array compilation requires a known length, is static, the type needs to be uniquely determined, the array is abstract class, the creation needs array.createinstance ();
  ArrayList compile-time length is unknown, is dynamic, and the added elements can be of different types.

4 List-apis

4-1 Introduction

list< t> is a generic class that implements an interface ilist< T>, and an external interface is displayed by using an array that is dynamically resized inside a size.

4-2 adding elements

Implementation to add an element

ADD (obj)

To add elements to the list in bulk:

AddRange (objlist)

Example:

        Private list<int> intlist = new list<int> ();        public void Addapi ()        {            intlist.add (10);//Add 1 elements            Intlist.addrange (new List<int> () {5, 1, 1, 2, 2, 3}); Add elements in bulk        }

Inserts an element from the collection at the specified index

void Insert (int index, T item);
void Insertrange (int index, IEnumerable "T" collection)

4-3 removing elements

Assume that Intlist is a list type with an initial value of {10,5,1,1,2,2,3}. Perform:

Intlist.remove (1);

Removes the first occurrence of a specific object from the Intlist. After removing element 1, intlist = {10,5,1,2,2,3};

Remove a range of elements:

Intlist.removerange (0, 2);

Intlist = {2,2,3};

After removing all duplicate elements: Intlist = {3};

            Intlist.removeall (removeduplicateelements);             Intlist.removeall (i =            {                list<int> elementlist = Intlist.findall (r = r.equals (i));                if (elementlist! = null && elementlist.count > 1)                    return true;                return false;            });

When you decide whether an element exists, such as removing an element, you need to use an equality comparer. If the type T implements the iequatable< t> generic interface, the equality comparer is the equals (T) method ; Otherwise, the default equality comparer is Object.Equals (Object).

Here is an example of an interface that is not the default comparator:

    public class MyObject {public int Value {get; set;} public MyObject (int value) {this.        Value = value; }}//Implement Interface Iequatable<myobject> public class Myobjectcollection:iequatable<myobject> {pri                    vate list<myobject> _myobjects = new list<myobject> () {New MyObject (3), New MyObject (4), New MyObject (3), New MyObject (2), New MyObject (3        )        };         Delete all duplicate elements public void RemoveDuplicates () {_myobjects.removeall (Equals);            } public list<myobject> Myobjects {get {return _myobjects; }} public bool Equals (MyObject other) {MyObject duplicate = _myobjects.find (R = > r.value = = other.                        Value);       if (duplicate! = null && duplicate!=other)                     return true;        return false; }    }

Equals (object) is implemented here, but remove (test) is temporarily unsuccessful and is later searched for a reason.

4-4 finding elements

Determines whether an element is in the list.

BOOL Contains (obj)

Determines whether to include elements that match the conditions defined by the specified predicate.

BOOL Exists (predicate<t> match)

Searches for an element that matches the conditions defined by the specified predicate, and returns the first matching element.

T Find (predicate<t> match)

Retrieves all elements that match the criteria defined by the specified predicate.

List<t> FindAll (predicate<t> match)

Searches for an element that matches the conditions defined by the specified predicate and returns the zero-based index of the first matching element

int FindIndex (predicate<t> match)

Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements from the specified index to the last element.

int findindex (int startIndex, predicate<t> match)

Searches for an element that matches the conditions defined by the specified predicate and returns the 0 index of the first occurrence within the range of elements that start at the specified index and contain the specified number of elements

int findindex (int startIndex, int count, predicate<t> match)
T FindLast (predicate<t> match)
int FindLastIndex (predicate<t> match)
int findlastindex (int startIndex, predicate<t> match)
int findlastindex (int startIndex, int count, predicate<t> match)

Searches for the specified object and returns the zero-based index of the first occurrence

int IndexOf (T item)

Searches for the specified object and returns the zero-based index of the first occurrence within the range of elements from the specified index to the last element

int IndexOf (T item, int index)
int IndexOf (T item, int index, int count)

Searches for the specified object and returns the zero-based index of the last occurrence.

int LastIndexOf (T item)
int LastIndexOf (T item, int index)
int LastIndexOf (T item, int index, int count)

4-5 Two-part search

Searches the entire sorted list for an element using the default comparer, and returns the zero-based index of the element.

int BinarySearch (T item);

Searches the entire sorted list for an element using the specified comparer, and returns the zero-based index of the element.

int BinarySearch (T item, icomparer<t> comparer)
int binarysearch (int index, int count, T item, icomparer<t> comparer)

4-6 sort

Use the default comparer to sort the elements in the entire list.

void Sort ()

Sorts the elements in the entire list using the specified System.comparison.

void Sort (comparison<t> Comparison)

Sorts the elements in the list using the specified comparer.

void Sort (icomparer<t> comparer)
void Sort (int index, int count, icomparer<t> comparer)

4-7 Performance Analysis

Operation complexity of Time
Add O (1) or O (n)
Insert O (N)
Remove O (N)
Getanitem O (1)
Sort O (nlogn), Worst O (n^2)
Find O (N)

4-8 using trap points:

1 list. Min () and list. The LINQ methods, such as Max () and Average (), when the list element is 0, the exception "sequence contains no elements" appears.

2 object. ToString () detects if object is null before it is used.

3 The iterator is not allowed to increment or delete when the foreach traversal is traversed. For example:

Public list<mdevice> getnormaldevices (list<mdevice> devices)    {        rtndevices = devices;        foreach (var device in devices)        {            var tmpdevices = Bslmdevice.getmdevicebydevicecode (device. Devicecode);                    if (!devices[0]. Isnormal)            {            //This is illegal because removing an element from the Rtndevices list is equivalent to removing the devices list.                rtndevices.remove (device);}}}    

5 SortedList

5-1 SortedList Introduction

Sorted shows that it is automatically sorted internally, and list shows that it is a bit like a list that can access the elements in the collection by index.

5-2 internal Implementation Mechanism

An SortedList object internally maintains 2 arrays to store the elements, one of which holds the key (keys), and the other holds the value associated with the key (values). Each element is a key-value pair (Key/value pair). Key cannot be null,value.

5-3 Summary API

5-3-1 capacity

The capacity of a SortedList object is the number of elements that the SortedList can hold, which is dynamically changed and automatically adjusted. As shown below:

SortedList MYSL = new SortedList () Mysl.add ("Third", "!"); Mysl.add ("Second", "World"), Mysl.add ("First", "Hello"); Console.WriteLine ("Mysl"); Console.WriteLine ("  Capacity: {0}", mysl.capacity);

At this time capacity:16

If the number of elements added to the MYSL increases, the corresponding capacity will automatically become larger.

5-3-2 accessing elements

Access by index

SortedList object to access through index, you need to use the constructor SortedList () or SortedList (IComparer icompared).

SortedList SortedList = new SortedList () Sortedlist.add (3, "GZ"), Sortedlist.add (9, "LHX"), Sortedlist.add (3, "gz"); o Bject Getbyindex = Sortedlist.getbyindex (2);

Access via key

SortedList object to access through key, you need to use a generic constructor with Tkey,tvalue.

sortedlist<int,string> SortedList = new sortedlist<int,string> () Sortedlist.add (3, "GZ"); Sortedlist.add (9, "LHX"); object getbyindex = Sortedlist[3];

5-3-3 sort

SortedList has a default comparison order, such as the following code:

sortedlist<int,string> SortedList = new sortedlist<int,string> () Sortedlist.add (9, "GZ"); Sortedlist.add (3, "LHX");

The result is that the first pair in SortedList is 3, "LHX"

If you do not want to follow the default sort order, you need to customize a sort order at construction time, such as the following code:

Implementing a Sort interface

Create a new private sort class to implement the interface IComparer

Private class implementicompare:icomparer<int>  {public      int Compare (int x, int y)      {          return x < Y? 1:-1;      }  }

Construction SortedList

Implementicompare implecompare = new Implementicompare (); Sortedlist<int, string> SortedList = new Sortedlist<int, string> (Implecompare); Sortedlist.add (9, "GZ"); Sortedlist.add (3, "LHX");

Sorted by key from large to small, the result is the first pair in SortedList is 9, "GZ"

5-3-4 adding elements

Adding an element to the collection with the Add interface implementation does not allow the same key to be added repeatedly.

sortedlist<int,string> SortedList = new sortedlist<int,string> () Sortedlist.add (9, "GZ"); Sortedlist.add (3, "LHX");

5-3-5 removing elements

Removes the specified element from the collection, remove (object removedelement), and specifies that the element removeat (int index) be removed at index.

Remove (object)

SortedList MYSL = new SortedList () Mysl.add ("3c", "dog"), Mysl.add ("2c", "over"), Mysl.add ("3a", "the"), Mysl.add ("3b" , "lazy");   Mysl.remove ("3b"); Sucessful to remove
Sortedlist<int, string> SortedList = new Sortedlist<int, string> (); Sortedlist.add (9, "GZ"); Sortedlist.add (3, "LHX"); bool Removedflag = Sortedlist.remove (3); True
Implementicompare implecompare = new Implementicompare (); Sortedlist<int, string> SortedList = new Sortedlist<int, string> (Implecompare); Sortedlist.add (9, "GZ"); Sortedlist.add (3, "LHX"); bool Removedflag = Sortedlist.remove (3); False

This is a place to note that when a constructor with Implecompare implements a sort interface, it seems that an element cannot be removed and needs to be confirmed.

RemoveAt (int index)

SortedList sorted = new SortedList (); sorted. ADD (9, "GZ"); sorted. ADD (3, "LHX"); Sortedlist.removeat (1); After the sorted position is removed, a pair of SortedList keys is 3, the second pair has a key of 9, so the key value of 9 is removed.

5-4 Performance

A sortedlist operation is slower than the Hashtable object, because it implements the sort function. However, SortedList provides the convenience of access, because the element can be accessed either by index or by key.

6. NET container-related interfaces

Interface Description
ienumerable< t> Implementing the Foreach statement requires implementing this interface, and the interface method GetEnumerator returns an enumerator.
icollection< t> Method: Count property, CopyTo (Array), Add, Remove, Clear
ilist< t> Defines the Indexer,insert, RemoveAt Method, inherited icollection< t>
iset< t> Method: Seek the set, intersection, inherit from icollection< t>
idictionary< TKey, tvalue> A collection of key and value implementations
ilookup< TKey, tvalue> Similarly, allow multiple values with one key.
icomparer< t> Comparer implementation, sorting comparison rules
iequalitycomparer< t> object is compared for equality another object
iproducerconsumercollection< t> Thread-safe collection Classes



7 Interface UML





8 time complexity of each container

collection type ADD Insert Remove Item Sort Find
list< t> O (1) or O (n) O (N) O (N) O (1) O (NLOGN) O (N)
stack< t> O (1) or O (n) Not applicable Pop () O (1) Not applicable Not applicable Not applicable
queue< t> O (1) or O (n) Not applicable O (1) Not applicable Not applicable Not applicable
hashset< t> O (1) or O (n) O (1) or O (n) O (1) Not applicable Not applicable Not applicable
linkedlist< t> O (1) O (1) O (1) O (N) Not applicable O (N)
Dictionary<, > O (1) or O (n) Not applicable O (1) O (1) Not applicable Not applicable
Sorteddictionary<,> O (LOGN) Not applicable O (LOGN) O (LOGN) Not applicable Not applicable
Sortedlist<,> O (LOGN) Not applicable O (N) O (LOGN) Not applicable Not applicable

The above is the C # container class, interface, performance detailed description of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.