C#数组知识总结

一、数组的概念

是一种数据类型,可存储一组数据


二、数组的声明

//语法:
数据类型【】数组名;

//声明类型:
            int[] score;    //存储成绩,整型
            int[] height;   //存储高度,浮点型
            int[] name;     //存储姓名,字符串型


三、数组的大小(给数组分配空间)

一旦声明了数组的大小,就不能修改

语法:
数组名 = new 数据类型【数组长度】

在声明数组时便分配数组空间的两种方法

//法1:数据类型【】数组名 = new 数据类型【数组长度】
int [] score = new int [] {90,85,87,91,78};
//法2:数据类型【】数组名 = {值1,值2,值3
int [] score = {90,85,87,91,78};


四、访问数组

数组元素是通过下标来访问的

语法:
数组名【下标号】
例如向数组score中存放数据
score【0】=26;
赋值时使用for循环更加方便


五、数组的使用


1.数组的遍历

这种方法可以在不知道索引的前提下,依次访问数组中所有元素,具体需要使用foreach语句
代码如下:
        static void Main(string[] args)
        {
            int[] myArray = new int[5] { 1, 2, 3, 4, 5 };

            //采用foreach语句对myArray进行遍历
            foreach (int number in myArray)
            {
                Console.WriteLine(number);
            }
            Console.ReadKey();     
        }


2.使用索引访问数组


3.数组元素清空

使用Array.Clear方法可清空数组元素(由于数组元素值初始后不可更改,所以清空元素后,元素的值显示为0)


4.数组的查找

这里提供了两个方法:Array.IndexOf和Array.LastIndexOf


5.数组的排序方法

Sort方法排序

            int[] myArray = { 13,27,46,39,62,83,27,36};
            Console.WriteLine("数组排列前");
            foreach (int i in myArray)
            {
                Console.Write(i);
                Console.Write(" ");
            }
             
            Console.WriteLine("\n");
            Console.WriteLine("指定数组元素排序");
            //对数组中所有元素排序
            Array.Sort(myArray);
            foreach (int i in myArray)
            {
                Console.Write(i);
                Console.Write(" ");
            }
            Console.ReadLine();



冒泡排序

static List<int> list = new List<int>() { 72, 54, 59, 30, 31, 78, 2, 77, 82, 72 };
     
static void Main(string[] args)
{
    Bubble();
    PrintList();
}
 
static void Bubble()
{
    int temp = 0;
    for (int i = list.Count; i > 0; i--)
    {
        for (int j = 0; j < i - 1; j++)
        {
            if (list[j] > list[j + 1])
            {
                temp = list[j];
                list[j] = list[j + 1];
                list[j + 1] = temp;
            }
        }
        PrintList();
    }
}
 
private static void PrintList()
{
    foreach (var item in list)
    {
        Console.Write(string.Format("{0} ", item));
    }
    Console.WriteLine();
}

猜你喜欢

转载自blog.csdn.net/delicious_life/article/details/80425103
今日推荐