C#note 04: array and collections

Arrays and Collections

Storing groups of related items of data is a basic requirement of most software applications; the two primary was of doing this are with arrays and collections.

Arrays are collections of objects of the same type. Because arrays can be almost any length, they can be used to store thousands or even millions of objects, but the size must be decided when the array is created. Each item in the array is accessed by an index, which is just a number that indicates the position or slot where the object is stored in the arrsy. Arrays can be used to store both Reference Types and Value Types.

Single-Dimensional Arrays

An array is an indexed collection of objects. A single-dimensional array of objects is declared like this: type[] arrayName

Often, you initialize the elements in the array at the same time, like this: 

int[] array = new int[5];

The default value of numberic array elements is zero, and reference elements default to null, but you can initialize values during array create, like this: 

int[] array1 = new int[] {1, 3, 5, 7, 9};

int[] array2 = {1, 3, 5, 7, 9};

Arrays use zero-based indexes, so that the first element in the array is element 0.

Multidientsional Arrays

Conceptually, a multidimensional array with two dimensions resembles a grid. A multidimensional array with three dimensions resembles a cube.

Jagged Arrays

A variation of the multidimensional array is the jagged array: an array of arrays. A jagged array is a single-dimensional array, and each eleent is itself an array. The element arrays are not required to all be of the same size.

Using the foreach Statement

The foreach statement is often used to access each element stored in an array.

Arrays of Objects

Creating an array of objects, rather than an array of simple data types such as integers, is a two-part process. First you declare the array, and then you must create the objects that are stored in the array. 

Collections

An array is just one of many options for storing sets of data by using C#. The option that you select depends on several factors, such as you intend to manipulate or access the items. For example, a list is generally faster than an array if you must insert items at the beginning or in the middle of the collections. Other types of collection classes include map, tree, and stack; each one has its own advantages. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值