6 common collection classes in C #

Source: Internet
Author: User

first, to say that the array is not enough (also can say the difference between the collection and the array)

1. The array is fixed in size and cannot be scaled. Although System.Array.Resize this generic method resets the size of the array, the method is to recreate the new set size array with the elements of the old array initialized. Then the previous array is discarded! And the collection is variable-length.

2. Array to declare the type of the element, the element type of the collection class is object.

3. Array readable and writable can not declare only reading group. Collection classes can provide readonly methods to use collections in read-only mode.

4. An array must have an integer subscript to access a particular element, yet many times such subscripts are not very useful. The collection is also a list of data without using subscript access. Many times the collection has a custom subscript type, for queues and stacks do not support subscript access!

Two, the following 6 kinds of common collections

1.ArrayList class

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
...{
class Program
...{
static void Main(string[] args)
...{
ArrayList al = new ArrayList();
al.Add(100);//单个添加
foreach (int number in new int[6] ...{ 9, 3, 7, 2, 4, 8 })
...{
al.Add(number);//集体添加方法一
}
int[] number2 = new int[2] ...{ 11,12 };
al.AddRange(number2);//集体添加方法二
al.Remove(3);//移除值为3的
al.RemoveAt(3);//移除第3个
ArrayList al2 = new ArrayList(al.GetRange(1, 3));
//新ArrayList只取旧ArrayList一部份
Console.WriteLine("遍历方法一:");
foreach (int i in al)//不要强制转换
...{
Console.WriteLine(i);//遍历方法一
}
Console.WriteLine("遍历方法二:");
for (int i = 0; i != al2.Count; i++)//数组是length
...{
int number = (int)al2[i];//一定要强制转换
Console.WriteLine(number);//遍历方法二
}
}
}
}

Figure 1

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.