C # collection 1

Source: Internet
Author: User
Tags type casting

Before we talk about the collection, let's start with a little episode--The Richter shift.

--Richter Conversion

Two features of the Richter conversion

    1. Subclasses can be assigned to a parent class: if there is a place that requires a parent class as an argument, we can give a subclass instead
    2. If a child class object is loaded in the parent class, you can cast the parent object to the corresponding subclass object

is and as for type casting
is--returns True if the conversion succeeds, otherwise false

//假设有两个类,一个Person类,一个Son类//Son类继于Person类new Son();ifis Son){    Son s = (Son)p;}else{    Console.WriteLine("转换失败")}

as--returns an object of the corresponding type if it can be converted, otherwise returns null

//那么上面的转化就可以这样玩儿newas Son;
--arraylist Collection

The set solves the defect of fixed length of array, ArrayList collection contains various element types, and resolves the single defect of array element type.

//创建一个集合对象listnew ArrayList();

Methods of ArrayList

    • new Element
      • Add ()--Add a single element at the end of the add
      • AddRange ()--Add the collection, add at the end, and then extract each element of the collection to add
      • inse RT (Specify index, insert content)--insert a single element before the specified index
      • insertrange (specify index, inserted collection)--insert a collection before the specified position
    • Delete element
      • Clear ()--empty collection
      • Remove (the element to delete)--delete the specified element
      • RemoveAt (subscript)--delete the element with the specified subscript
      • RemoveRange (start position, end position)--delete elements within a specified range
    • Other methods
      • Sort ()--Ascending order
      • Reverse ()--Flip
      • Contains (Specify content)--determine if the specified content exists
listnew ArrayList();list.Add(1);list.Add(2.0);list.Add("hello");list.Add("world");//集合的元素数量用Count来表示,不是Lengthfor (int0list.Count; i++){    Console.Write(list[i]+"\t");}//输出   1       2       hello   world

One more example.

//above are some value types, so let's see what we can do to add reference typesArrayListList=NewArrayList ();List. ADD ("Hello");List. ADD (New int[] {1,2,3,4}); for(inti =0; I <List. Count; i++) {Console.Write (List[i]+"\ T");}//Output Hello system.int32[]--This is the namespace of the array//If the output is not a namespace, you need to add the collection using the AddRange () method//Why output namespaces, each element added to the ArrayList collection will be converted to the object type//Because the object class is the parent class (base class) for all classes, it is allowed to add arbitrary data types to the collection

Optimization of the above example

ArrayListList=NewArrayList ();List. ADD ("Hello");List. ADD (New int[] {1,2,3,4}); for(inti =0; I <List. Count; i++) {//judgment is not converted from array to object[], Richter conversion     if(List[I] isint[])        {//(int[]) list[i]) convert to subclass Array, Richter conversion           for(intj =0; J < (int[])List[i]). Length; J + +) {Console.Write ((int[])List[i]) [j]+"\ T"); }         }Else{Console.Write (List[i]+"\ T"); }  }//Output Hello 1 2 3 4  //Above This process has occurred unpacking and boxing operations, affecting performance, but there is no way  //unboxing: Conversion of reference types to value types  //Boxing: value type converted to reference type  //unpacking and boxing are prerequisites for an inheritance relationship

The length of the collection issue:
When the number of elements actually contained in the collection (count) exceeds the number of elements that can be contained (capcity),
The collection will open up to one more space in memory to ensure that the length of the collection is always sufficient.

Hashtable collection

The Hashtable collection is a set of key-value pairs that, in the set of key-value pairs, are searched by the key, the key must be unique, and count gets the number of key-value pairs in the Hashtable collection

    • New data for Hashtable
      • add--This method to add the same key will throw an exception, so generally first contains judgment
      • ["Key"]= value-this is the form of adding data, if the plan and in the already have this key, then the original key will be overwritten
new Hashtable();if (!_hs.Contains("姓名")) {     _hs.Add("姓名""张三"); } _hs["性别""男";

Ways to Traverse Hashtable

foreach(var  集合中的每一项  in  集合名称){}

Example 1,

new Hashtable();ht["name""HelloWorld";ht["hobby""Programming";foreach (varin ht.Keys){     Console.Write(hs[key]+"\t");}//输出:  HelloWorld      Programming//ht.Keys指定了键组成的集合,key在每次循环中代表键集合中的值

Example 2,

new Hashtable();ht["name""HelloWorld";ht["hobby""Programming";foreach (varvaluein ht.Values){    Console.Write(value+"\t");}//输出:  HelloWorld      Programming//ht.Values指定了值组成的集合,key在每次循环中代表值集合中的值
    • Methods for Hashtable collections
      • Contains and (key name)--Determine if you have the specified key
      • ContainsKey (key Name)--Determine if you have a specified key (common this)
      • Clear ()--empty
      • Remove (key Name)--Remove

C # collection 1

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.