C#数据结构和算法 [Arrays and ArrayLists]

Arrays and ArrayLists

The array is the most common data structure, present in nearly all programming
languages. Using an array in C# involves creating an array object of
System.Array type, the abstract base type for all arrays. The Array class provides
a set of methods for performing tasks such as sorting and searching that
programmers had to build by hand in the past.
An interesting alternative to using arrays in C# is the ArrayList class. An
arraylist is an array that grows dynamically as more space is needed. For
situations where you can’t accurately determine the ultimate size of an array,
or where the size of the array will change quite a bit over the lifetime of a
program, an arraylist may be a better choice than an array.
In this chapter, we’ll quickly touch on the basics of using arrays in C#,
then move on to more advanced topics, including copying, cloning, testing
for equality and using the static methods of the Array and ArrayList
classes.

Arrays 和 ArrayLists
数组是最常用的数据结构,几乎在所有的编程语言中都会出现。在C#里用数组的话需要建立一个System.Array类型的对象,它是所有数组的抽象基类。
Array类提供了一组过去需要程序员手动完成的方法,比如排序和查找。
另一个可以建立数组的替代品是ArrayList,ArrayList是可以按需要动态增长的数组。
在不能确定一个数组的大小的情况下,或在程序的生命周期内数组的大下需要改变时,ArrayList是个好的选择。
本章会快速了解一下C#里数组的基础,然后转向深层的主题,包括拷贝,克隆,比较是否相等以及用Array和ArrayList的静态方法。
ARRAY BASICS
Arrays are indexed collections of data. The data can be of either a built-in
type or a user-defined type. In fact, it is probably the simplest just to say that
array data are objects. Arrays in C# are actually objects themselves because
they derive from the System.Array class. Since an array is a declared instance

of the System.Array class, you have the use of all the methods and properties
of this class when using arrays.
数组基础
数组是一组索引数据的集合。这些数据可以是任何内建类型。其实,可以简单地认为数组数据是对象。
C#里的数组就是对象本身,因为它派生自System.Array类。
声明一个System.Array类的一个实例后,你就可以用这个类的所有方法了。

Declaring and Initializing Arrays
Arrays are declared using the following syntax:
type[] array-name;
where type is the data type of the array elements. Here is an example:
string[] names;
A second line is necessary to instantiate the array (since it is an object of
System.Array type) and to determine the size of the array. The following line
instantiates the names array just declared:
names = new string[10];
and reserves memory for five strings.
声明和初使化数组
数组声明时用下面的格式:

type[] array_name;
type就是数据类型,比如
string[] names;

第二行需要实例化这个数组(因为是System.Array类型)并指定数组的大小。代码如下:
names = new string[10];
这样就为10个字符串分配了内存。

You can combine these two statements into one line when necessary to do
so:
string[] names = new string[10];
There are times when you will want to declare, instantiate, and assign data
to an array in one statement. You can do this in C# using an initialization
list:
int[] numbers = new int[] {1,2,3,4,5};
The list of numbers, called the initialization list, is delimited with curly braces,
and each element is delimited with a comma. When you declare an array
using this technique, you don’t have to specify the number of elements. The
compiler infers this data from the number of items in the initialization
list.
也可以两句合在一起写:

string[] names = new string[10];
有时候你想把声明,实例化,指定数据三个步骤同时进行,那就这样子:
int[] numbers = new int[] {1,2,3,4,5};
这一串数字,叫做初使化列表,用花括号括起来,每个元素用逗号隔开。
当用这种方式声明数组时,不用指定数组大小,编译器会自动根据初使化列表的个数来指定。

Setting and Accessing Array Elements
Elements are stored in an array either by direct access or by calling the Array
class method SetValue. Direct access involves referencing an array position by
index on the left-hand side of an assignment statement:
Names[2] = "Raymond";
Sales[19] = 23123;
The SetValue method provides a more object-oriented way to set the value
of an array element. The method takes two arguments, an index number and
the value of the element.
names.SetValue[2, "Raymond"];
sales.SetValue[19, 23123];
Array elements are accessed either by direct access or by calling the
GetValue method. The GetValue method takes a single argument—an index.
myName = names[2];
monthSales = sales.GetValue[19];
设定和存取数组元素
数组元素的存储既可以直接存储,也可以调用SetValue方法,直接存储方法需要用索引指定数组内的位置,向下面这样:

Names[2] = "Raymond";
Sales[19] = 23123;
SetValue方法提供了一个更面向对象的做法去设置数组元素的值,此方法有两个参数,一个是索引数,另一个是值。
names.SetValue[2, "Raymond"];
sales.SetValue[19, 23123];
数组元素的取出既可以直接取得,也可以调用GetValue方法,GetValue用一个简单的参数:索引数

myName = names[2];
monthSales = sales.GetValue[19];

It is common to loop through an array in order to access every array element
using a For loop. A frequent mistake programmers make when coding the loop
is to either hard-code the upper value of the loop (which is a mistake because
the upper bound may change if the array is dynamic) or call a function that
accesses the upper bound of the loop for each iteration of the loop:
(for int i = 0; i <= sales.GetUpperBound(0); i++)
totalSales = totalSales + sales[i];
Methods and Properties for Retrieving Array Metadata
The Array class provides several properties for retrieving metadata about an
array:
Length: Returns the total number of elements in all dimensions of an array.
GetLength: Returns the number of elements in specified dimension of an
Rank: Returns the number of dimensions of an array.
GetType: Returns the Type of the current array instance.
通过循环去取得数组内的每个元素是很常见的。程序员写循环时会经常犯一个错误:就是写死了循环的上限或调用取得上限的方法。
错误主要是因为数组的上限是动态的
for (int i = 0; i <= sales.GetUpperBound(0); i++)
totalSales = totalSales + sales[i];
检索数组元数据的方法和属性:
Length:返回数组元素的所有个数。
GetLength:返回数组元素一维内的个数。
Rank:返回维数
GetType:返回当前数组实例的类型

The Length method is useful for counting the number of elements in a
multidimensional array, as well as returning the exact number of elements in
the array. Otherwise, you can use the GetUpperBound method and add one
to the value.
Since Length returns the total number of elements in an array, the
GetLength method counts the elements in one dimension of an array. This
method, along with the Rank property, can be used to resize an array at runtime
without running the risk of losing data. This technique is discussed later
in the chapter.
The GetType method is used for determining the data type of an array in
a situation where you may not be sure of the array’s type, such as when the
array is passed as an argument to a method. In the following code fragment,
we create a variable of type Type, which allows us to use call a class method,
IsArray, to determine if an object is an array. If the object is an array, then the
code returns the data type of the array.
Length方法在统计多维数组内元素的个数时很有用。要不然就用GetUpperBound方法+1取这个值
因为Length方法返回的是数组内所有元素的个数,GetLength方法返回的是一维内数组的个数。
Rank属性可以在运行时改变数组的大小而不用担心丢失数据,这个在章节后面详细讨论。
GetType方法是当你确定不了数组类型时用来判定数据类型的方法,比如数组是入参。
下面的代码,会创建一个Type类型的变量,允许我们调用一个类方法:IsArray()来判定这个对象是否是数组,
如果是数组的话,那么就返回数组的数据类型
int[] numbers;
numbers = new int[] {0,1,2,3,4};
Type arrayType = numbers.GetType();
if (arrayType.IsArray)
Console.WriteLine("The array type is: {0}", arrayType);
else
Console.WriteLine("Not an array");
Console.Read();

The GetType method returns not only the type of the array, but also lets us
know that the object is indeed an array. Here is the output from the code:
The array type is: System.Int32[]
The brackets indicate the object is an array. Also notice that we use a format
when displaying the data type. We have to do this because we can’t convert
the Type data to string in order to concatenate it with the rest of the displayed
string.
GetType方法不仅返回数组的类型,也告诉我们数组其实是一个对象,下面是输出的代码:
The array type is: System.Int32[]
方括号说明这个对象是个数组,也注意一下当显示数组类型时我们使用的格式。
知道了这个,我们不能转换把这个类型转换成string去连接剩下的字符串

30 ARRAYS AND ARRAYLISTS
Multidimensional Arrays
So far we have limited our discussion to arrays that have just a single dimension.
In C#, an array can have up to 32 dimensions, though arrays with more
than three dimensions are very rare (and very confusing).
Multidimensional arrays are declared by providing the upper bound of each
of the dimensions of the array. The two-dimensional declaration:
int[,] grades = new int[4,5];
declares an array that consists of 4 rows and 5 columns. Two-dimensional
arrays are often used to model matrices.
You can also declare a multidimensional array without specifing the dimension
bounds. To do this, you use commas to specify the number of dimensions.
double[,,] sales;
For example,
double[,] Sales;
declares a two-dimensional array, whereas
double[,,] sales;
declares a three-dimensional array. When you declare arrays without providing
the upper bounds of the dimensions, you have to later redimension the
array with those bounds:
sales = new double[4,5];
多维数组
目前我们的讨论都限于一维数组,C#里,可以用最多32维的数组,虽然3维以上的数组就不常用了(还混乱的很)。
多维数组是用指定了每维上限的数组声明的,2维的声明:
int[,] grades = new int[4,5];
声明一个4行5列的数组,2维数组一般用来模拟矩阵。
你也可以声明一个不指定每一维的上限的多维数组,用逗号分开就行了。
举个例子:
double[,] Sales;
声明一个2维数组,
double[,,] sales;
声明一个3维数组,当你声明数组不指定某维的上限时,用的时候要指定
sales = new double[4,5];

Multidimensional arrays can be initialized with an initialization list. Look
at the following statement:
Int[,] grades = new int[,] {{1, 82, 74, 89, 100},
{2, 93, 96, 85, 86},
{3, 83, 72, 95, 89},
{4, 91, 98, 79, 88}}
First, notice that the upper bounds of the array are not specified. When you
initialize an array with an initialization list, you can’t specify the bounds of
the array. The compiler computes the upper bounds of each dimension from
the data in the initialization list. The initialization list itself is demarked with
curly braces, as is each row of the array. Each element in the row is delimited
with a comma.
多维数组也可以用初使化列表,看下面的代码:
Int[,] grades = new int[,] {{1, 82, 74, 89, 100},
{2, 93, 96, 85, 86},
{3, 83, 72, 95, 89},
{4, 91, 98, 79, 88}}
首先,注意数组的上限是没有指定的,当用初使化列表来初使化一个数组时,
不能指定该数组的上限。编译器会通过初使化列表计算每一维的上限。
初使化列表本身是一对花括号,每一行,每一个元素都用逗号分开。

Accessing the elements of a multidimensional array is similar to accessing
the elements of a one-dimensional array. You can use the traditional array
access technique,
grade = Grades[2,2];
Grades[2,2] = 99
or you can use the methods of the Array class:
grade = Grades.GetValue[0,2]
You can’t use the SetValue method with a multidimensional array because the
method only accepts two arguments: a value and a single index.
取得多数组的元素和一维是差不多的,传统技术是这样的:

grade = Grades[2,2];
Grades[2,2] = 99
或者也可以用GetValue方法
grade = Grades.GetValue[0,2];

但不能用SetValue方法来设置多维数组的数据,因为这个方法只有两个参数。
It is a common operation to perform calculations on all the elements of
a multidimensional array, though often based on either the values stored in
the rows of the array or the values stored in the columns of the array. Using
the Grades array, if each row of the array is a student record, we can calculate
the grade average for each student as follows:
在多维数组里计算所有元素是很常见的操作,虽然常常时是基于某一行或某一列的数据。
用Grades这个数组,如果数组的每一行是一条学生记录,我们可以计算年级里每个学生的平均分:

  
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值