数组与集合(Visual C# 速成版)

更新:2007 年 11 月

存储相关数据项组是大多数软件应用程序的一项基本要求;这可以通过使用数组和集合这两种主要方式来实现。

数组

数组是相同类型的对象的集合。由于数组几乎可以为任意长度,因此可以使用数组存储数千乃至数百万个对象,但必须在创建数组时就确定其大小。数组中的每项都按索引进行访问,索引是一个数字,指示对象在数组中的存储位置或槽。数组既可用于存储引用类型,也可用于存储值类型

一维数组

数组是一个经过索引的对象集合。一维对象数组的声明如下:

type[] arrayName;

一般会同时初始化数组中的元素,如下所示:

int[] array = new int[5];

数值数组元素的默认值为零,引用元素的默认值为 null,但您可以在创建数组的过程中初始化值,如下所示:

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

或者甚至这样来初始化:

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

数组的索引从零开始,因此数组中的第一个元素为元素 0。

string[] days = {"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat"};
System.Console.WriteLine(days[0]);  // Outputs "Sun"

多维数组

从概念上来说,两维数组类似于网格,三维数组则类似于立方体。

// declare multidimension array (two dimensions)
int[,] array2D = new int[2,3];


// declare and initialize multidimension array
int[,] array2D2 = { {1, 2, 3}, {4, 5, 6} };


// write elements in a multidimensional array
for (int i=0; i<2; i++)
{
    for (int j=0; j<3; j++)
    {
        array2D[i,j] = (i + 1) * (j + 1);
    }
}


// read elements in a multidimensional array
for (int i=0; i<2; i++)
{
    for (int j=0; j<3; j++)
    {
        System.Console.Write(array2D[i,j]);
    }
    System.Console.WriteLine();
}

交错数组

多维数组的一种变体是交错数组,即由数组组成的数组。交错数组是一维数组,且每个元素自身是一个数组。作为元素的数组无需均为相同的大小。

声明交错数组的方式如下:

int[][] jaggedArray = new int[3][];

这样做会创建一个有 3 个数组的数组。这些数组可以按如下方式初始化:

jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];

使用 foreach 语句

foreach 语句通常用来访问数组中存储的每个元素:

int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
foreach (int i in numbers)
{
    System.Console.Write("{0} ", i);
}
//Output: 4 5 6 1 2 3 -2 -1 0

对象数组

创建对象数组(而非创建像整数这样的简单数据类型的数组)的过程分为两个部分。首先声明数组,然后必须创建存储在数组中的对象。本示例创建一个定义一个音频 CD 的类。然后创建一个存储 20 个音频 CD 的数组。

namespace CDCollection
{
    // Define a CD type.
    class CD
    {
        private string album;
        private string artist;
        private int rating;

        public string Album
        {
            get {return album;}
            set {album = value;} 
        }
        public string Artist
        {
            get {return artist;}
            set {artist = value;}
        }
        public int Rating
        { 
            get {return rating;} 
            set {rating = value;} 
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Create the array to store the CDs.
            CD[] cdLibrary = new CD[20];

            // Populate the CD library with CD objects.
            for (int i=0; i<20; i++)
            {
                cdLibrary[i] = new CD();
            }

            // Assign details to the first album.
            cdLibrary[0].Album = "See";
            cdLibrary[0].Artist = "The Sharp Band";
            cdLibrary[0].Rating = 10;
        }
    }
}

集合

对于使用 C# 存储数据集而言,数组只是众多选择中的一种。而具体的选择取决于若干因素,如操作或访问项所要采取的方式。例如,如果需要在集合的开头或中间插入项,则“列表”的速度一般比数组快。其他类型的集合类包括映射、树和堆栈,每种类型均有各自的优点。有关更多信息,请参见 System.CollectionsSystem.Collections.Generic

下面的示例显示如何使用 List<T> 类。注意,与 Array 类不同,可以在列表中间插入项。本示例限制列表中的项必须是字符串。

public class TestCollections
{
    public static void TestList()
    {
        System.Collections.Generic.List<string> sandwich = new System.Collections.Generic.List<string>();

        sandwich.Add("bacon");
        sandwich.Add("tomato");

        sandwich.Insert(1, "lettuce");

        foreach (string ingredient in sandwich)
        {
            System.Console.WriteLine(ingredient);            
        }
    }
}

请参见

任务

如何:声明数组 (Visual C#)

如何:将 Object 数组传递给方法 (Visual C#)

如何:循环访问数组 (Visual C#)

如何:初始化数组 (Visual C#)

如何:循环访问集合 (Visual C#)

概念

C# 语言入门

参考

数组(C# 编程指南)

集合类(C# 编程指南)

泛型介绍(C# 编程指南)

Array