C # Learning-Set

Source: Internet
Author: User

Directory

  • List of sets and Their Implemented interfaces
  • Array, Indexer
  • List
  • Queue
  • Stack
  • Linked List
  • Ordered table
  • Dictionary
  • LookUp
  • HashSet
  • Bit Array

In the previous article, the generic type is described, as shown in the directory, which summarizes the commonly used sets.

  • List of sets and Their Implemented interfaces

The following lists the commonly used collection classes and the Set interfaces implemented by these classes:

Collection class

Set Interface

ArrayList

IList, ICollection, IEnumerable

Queue

ICollection, IEnumerable

Stack

ICollection, IEnumerable

BitArray

ICollection, IEnumerable

Hashtable

IDictionary, ICollection, IEnumerable

SortedList

IDictionary, ICollection, IEnumerable

List <T>

IList <T>, ICollection <T>, IEnumerable <T>, IList, ICollection, IEnumerable

Queue <T>

IEnumerable <T>, ICollection, IEnumerable

Stack <T>

IEnumerable <T>, ICollection, IEnumerable

Revoke list <T>

IEnumerable <T>, ICollection <T>, ICollection, and IEnumerable

HashSet <T>

IEnumerable <T>, ICollection <T>, IEnumerable

Dictionary <TKey, TValue>

IDictionary <TKey, TValue>,

ICollection <KeyValuePair <TKey, TValue>,

IEnumerable <KeyValuePair <TKey, TValue>,

IDictionary, ICollection, IEnumerable

SortedDictionary <TKey, TValue>

IDictionary <TKey, TValue>,

ICollection <KeyValuePair <TKey, TValue>,

IEnumerable <KeyValuePair <TKey, TValue>,

IDictionary, ICollection, IEnumerable

SortedList <TKey, TValue>

IDictionary <TKey, TValue>,

ICollection <KeyValuePair <TKey, TValue>,

IEnumerable <KeyValuePair <TKey, TValue>,

IDictionary, ICollection, IEnumerable

Lookup <TKey, TElement>

LKoopup <TKey, TElement>,

IEnumerable <IGrouping <TKey, TElemet>, IEnumerable

  • Array, Indexer

Arrays are very familiar to everyone, so we will not describe them here. I need to point out the differences between the shortest copy and the deep assignment of arrays during the copy process and the precautions. First, let's take a look at the following code example:

Public class Element {public Element (int I) {this. index = I;} public int index;} class Program {static void Main () {// value type array int [] intArrA = new int [] {1, 2 }; int [] intArrB = new int [intArrA. length]; int index = 0; foreach (int I in intArrA) {intArrB [index ++] = I;} // Array. copy (intArrA, intArrB, intArrA. length) // reference type array Element [] elemArrA = new Element [] {new Element (11), new Element (22) }; Element [] elemArrB = new Element [elemArrA. length]; index = 0; foreach (Element e in elemArrA) {elemArrB [index ++] = e;} // Array. copy (elemArrA, elemArrB, elemArrA. length );//... }}

In the above Code, there are two int-type value-type arrays first. The foreach statement is used to assign the value of array A to array B, and then an array of two Element reference types, and perform the same value assignment. What are the differences between the two data types after the assignment method?

The intArrA value of the array is assigned to the intArrB array. The memory space of the values of the two array elements is independent of each other and irrelevant to each other. However, the data stored in the eleArrA and eleArrB arrays is somewhat subtle. The data stored in eleArrA and eleArrB is a reference to the memory address of the element object in the array eleArrA array. Let's test it, in the above Code, "//… Add the following code:

            intArrA[1] = 3;            Console.WriteLine(" intArrA[1].index = " + intArrA[1]);            Console.WriteLine(" intArrB[1].index = " + intArrB[1]);            elemArrA[1].index = 33;            Console.WriteLine(" elemArrA[1].index = " + elemArrA[1].index);            Console.WriteLine(" elemArrB[1].index = " + elemArrB[1].index);

View the result after running:

From the above results, we can see that when the value of the intArrA array's 2nd element value is changed to 3, the value of the 2nd elements in the intArrB array will not change; the difference is that in an array of the reference type, when the value of the 2nd elements of eleArrA is changed to 33, the values of the 2nd elements in the eleArrA and eleArrB arrays are all 33, this shows that the eleArrA and eleArrB array elements point to the same object memory. The following shows the differences between copying array values and copying by reference:

Next, return to the sample code at the beginning. We can see that these two statements are blocked:

 //Array.Copy(intArrA, intArrB, intArrA.Length); //Array.Copy(elemArrA, elemArrB, elemArrA.Length);

In fact, these two statements have the same processing effect as the foreach statement. They all copy the elements of array A to array B. Now, we can see what's going on with the replication. Therefore, when processing the referenced array, you should note that the shortest copy does not copy the array object, but only copies the reference pointing to the object.

Of course, compared with the light copy, the deep copy means that copying the past is not an object reference, but a new object with the same value as the source object. Make a slight change to the above Code:

            foreach (Element e in elemArrA)            {                elemArrB[index] = new Element(index);                elemArrB[index++].index = e.index;            }

Then the running result will be different from the previous one:

Next, let's look at the indexer.

We often access the elements of the array like this: intArrA [index] -- access the elements of the array through subscript. Sometimes, our collection class also wants to manipulate the subscript of the collection object to access the collection element, however, C # does not support the "[" and "]" operators as C ++ does. Therefore, C # provides the indexer, the same effect was achieved.

The indexer is a C # syntax structure. You can use the array square brackets syntax that we are familiar with to access the elements in the Collection class. The indexer is a special attribute that has get () and set () access methods to specify its behavior. The Declaration of the indexer is as follows:

Type this [type parameter] {get; set ;}

The "type" determines the type of the object returned by the indexer, and the "type parameter" specifies the available parameter indexes that contain the set of target objects. Although integers are usually used as index values, you can also use other types, including strings, or even provide an indexer with multiple parameters to create multi-dimensional arrays. This keyword is a reference to the object pointed to by the indexer. As a normal property, you must define the get () and set () access methods to determine how the request type is retrieved from the set or assigned to the set.

Public class MyList {public MyList (params String [] initStrArr) {// initialize the subitem capacity this. items = new String [256]; foreach (String s in initStrArr) {// note that although the String is of the reference type, // the C # compiler has processed it internally, // The value here is deep copy, instead of just copying the string reference items [ctr ++] = s ;}} // Add the subitem to the end of the list public void Add (String the) {if (ctr> = items. length) {throw new ArgumentOutOfRangeException ();} else {items [ctr ++] = ;}} // indexer public String this [int index] {get {if (index <0 | index> = items. length) {throw new ArgumentOutOfRangeException ();} return items [index];} set {if (index >= ctr) {throw new ArgumentOutOfRangeException ();} else {items [index] = value ;}} public int GetItemNum () {return ctr;} private String [] items; private int ctr = 0 ;}

The above Code creates a simple collection class, which can be accessed by the indexer through subscript.

Static void Main () {String [] resArr = new String [] {"zhangsan", "lisi", "wangwu", "zhaoliu"}; // create a list object, use the string number resArr to initialize the list MyList list = new MyList (resArr); // Add the subitem list to the list. add ("123456"); list. add ("987654"); list. add ("741852"); list. add ("369258"); // print the list subitem for (int I = 0; I <list. getItemNum (); I ++) {Console. writeLine ("list [{0}] = {1}", I, list [I]);}

The above code is relatively simple, and the detailed comments are not described. Run the code and check the result:

Therefore, the indexer is very useful.

  • List

 The. Net Library provides ArrayList and List classes for the dynamic List <T>. The usage of the List class in the System. Collections. Generic namespace is very similar to the ArrayList class in the System. Collection namespace. This section mainly discusses how to use the List <T> class.

<1>. Create a list

We know that generics are type-safe, so assume that we have the following statement:

            ArrayList objectList = new ArrayList();            List<int> list = new List<int>();

Then, we can Add any type of value to the objectList object through the Add method, and only int type values can be added to the list:

As we can see, when trying to add Object-type data to the list, the compiler will prompt a parameter error.

Above, we created a list set object by calling the default constructor. You must know that the set has two attributes, one of which is the Capacity of the set, the second is the Count of the number of elements in the collection. The two are not equal. The capacity of the Set indicates the number of elements in the set. The number of elements in the Set indicates the number of elements added to the set. The value of Capacity is always greater than or equal to the value of Count. The default constructor is used to create an empty list of collection objects. After an element is added to the list, the capacity of the List is expanded to four elements, if the number of elements to be added is greater than the current capacity of the list object, the list will automatically expand the list capacity by a factor of 2. For example, when five elements are added, the list capacity will be increased from 4 to 8.

In addition, you can call the parameter-passing constructor to create a list object of the specified capacity. When the number of elements added to the List reaches or exceeds the list capacity, the size of the List is increased by two times. If you need to remove the empty spaces in the list after adding the elements in the list, you can call list. trimExcess () method. Note: if the number of elements in the list exceeds 90% of the capacity, calling this method will not play any role.

1. Set Initiator

C #3.0 allows the use of the Set initialization tool to assign values to the set. The Set inspector is similar to the array inspector.

            List<int> intList = new List<int>() { 1, 2, 3};            List<String> strList = new List<string>() { "first string", "second string", "third string"};            List<Object> objList = new List<object>() { new Object(), new Object(), new Object()};

2. Add a list

The Add () method can be used to Add a single element. The AddRange () method can be used to Add list elements in batches:

            intList.Add(12);            intList.AddRange(new int[]{23, 34, 45, 56});            objList.Add(new Object());            objList.AddRange(new Object[]{new Object(), new Object()});

Tip: The set initiator can only be used to declare a set, and AddRange () can be called after the set is initialized.

3. Insert list

We can Insert an element at the specified position through the Insert () method or Insert a large number of elements through InsertRange. If the inserted index is greater than the number of elements in the Set, an ArgumentOutOfRangeException type exception is thrown.

            intList.Insert(3, 56);            intList.InsertRange(3, new int[] { 0, 1, 3});

4. Access Element

All classes that run the IList and IList <T> interfaces provide an indexer. Therefore, you can use the indexer to access the specified element by passing the element number, if you access all elements in the list, you can use for or foreach to traverse the list.

In addition, the List <T> class also provides the ForEach () method. He uses the Action <T> parameter declaration.

public void ForEach(Action<T> action);

Action <T> is a generic delegate. Its declaration prototype is as follows:

public delegate void Action<T> (T obj);

Let's take a look at the implementation of the ForEach () method:

        public class List<T> : IList<T>         {            private T[] items;            //...            public void ForEach(Action<T> action)             {                if (action == null)                    throw new ArgumentNullException("action");                foreach(T item in items)                {                    action(item);                }            }            //...        }

Because List <T> implements the IEnumerable interface, you can use foreach to traverse the List and use Action <T> to delegate the List data.

5. Delete Elements

You can delete the list elements according to the index, for example, intList. Remove (3); the statement will delete 4th elements.

In addition, you can directly pass the element to be deleted to the Remove () method to delete the element. However, it is faster to delete the element according to the index, because the element needs to be searched first after the object is deleted.

To delete multiple elements, call the RemoveRange () method. Delete all. You can call the clear () method. You can call the RemoveAll () method to delete all elements of a specified feature.

6. Search Elements

 

 

 

 

----------------------------------------------------------

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.