首页 > 其他分享 >数组

数组

时间:2023-03-31 11:26:10浏览次数:38  
标签:Console 数组 int WriteLine new array

一维数组

 

使用 new 运算符创建一维数组,该运算符指定数组元素类型和元素数。下面的示例声明一个包含五个整数的数组:


//数组初始化

int[] array = new int[5];
int[] array1 = new int[] { 1, 3, 5, 7, 9 };
string[] weekDays = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
在声明时初始化数组时,可以避免使用表达式和数组类型,如以下代码所示。这称为隐式类型数组
int[] array2 = { 1, 3, 5, 7, 9 };
string[] weekDays2 = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

可以在不创建数组变量的情况下声明数组变量,但在将新数组分配给此变量时必须使用该运算符。例如:

int[] array3;
array3 = new int[] { 1, 3, 5, 7, 9 };   // OK
//array3 = {1, 3, 5, 7, 9};   // Error

可以使用索引检索数组的数据。例如:

string[] weekDays2 = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

Console.WriteLine(weekDays2[0]);
Console.WriteLine(weekDays2[1]);
Console.WriteLine(weekDays2[2]);
Console.WriteLine(weekDays2[3]);
Console.WriteLine(weekDays2[4]);
Console.WriteLine(weekDays2[5]);
Console.WriteLine(weekDays2[6]);

/*Output:
Sun
Mon
Tue
Wed
Thu
Fri
Sat
*/

将 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

将数组作为参数传递

在下面的示例中,初始化字符串数组并将其作为参数传递给字符串的方法。该方法显示数组的元素。接下来,该方法反转数组元素,然后该方法修改数组的前三个元素。每个方法返回后,该方法表明按值传递数组不会阻止对数组元素的更改。DisplayArrayChangeArrayChangeArrayElementsDisplayArray

using System;

class ArrayExample
{
    static void DisplayArray(string[] arr) => Console.WriteLine(string.Join(" ", arr));

    // Change the array by reversing its elements.
    static void ChangeArray(string[] arr) => Array.Reverse(arr);

    static void ChangeArrayElements(string[] arr)
    {
        // Change the value of the first three array elements.
        arr[0] = "Mon";
        arr[1] = "Wed";
        arr[2] = "Fri";
    }

    static void Main()
    {
        // Declare and initialize an array.
        string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
        // Display the array elements.
        DisplayArray(weekDays);
        Console.WriteLine();

        // Reverse the array.
        ChangeArray(weekDays);
        // Display the array again to verify that it stays reversed.
        Console.WriteLine("Array weekDays after the call to ChangeArray:");
        DisplayArray(weekDays);
        Console.WriteLine();

        // Assign new values to individual array elements.
        ChangeArrayElements(weekDays);
        // Display the array again to verify that it has changed.
        Console.WriteLine("Array weekDays after the call to ChangeArrayElements:");
        DisplayArray(weekDays);
    }
}
// The example displays the following output:
//         Sun Mon Tue Wed Thu Fri Sat
//
//        Array weekDays after the call to ChangeArray:
//        Sat Fri Thu Wed Tue Mon Sun
//
//        Array weekDays after the call to ChangeArrayElements:
//        Mon Wed Fri Wed Tue Mon Sun

多维数组

数组可以有多个维度。例如,以下声明创建一个包含四行两列的二维数组。

int[,] array = new int[4, 2];

以下声明创建一个包含三维 4、2 和 3 的数组。

int[,,] array1 = new int[4, 2, 3];

可以在声明时初始化数组,如以下示例所示。

// Two-dimensional array.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// A similar array with string elements.
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" },
                                        { "five", "six" } };

// Three-dimensional array.
int[,,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } },
                                 { { 7, 8, 9 }, { 10, 11, 12 } } };
// The same array with dimensions specified.
int[,,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } },
                                       { { 7, 8, 9 }, { 10, 11, 12 } } };

// Accessing array elements.
System.Console.WriteLine(array2D[0, 0]);
System.Console.WriteLine(array2D[0, 1]);
System.Console.WriteLine(array2D[1, 0]);
System.Console.WriteLine(array2D[1, 1]);
System.Console.WriteLine(array2D[3, 0]);
System.Console.WriteLine(array2Db[1, 0]);
System.Console.WriteLine(array3Da[1, 0, 1]);
System.Console.WriteLine(array3D[1, 1, 2]);

// Getting the total count of elements or the length of a given dimension.
var allLength = array3D.Length;
var total = 1;
for (int i = 0; i < array3D.Rank; i++)
{
    total *= array3D.GetLength(i);
}
System.Console.WriteLine("{0} equals {1}", allLength, total);

// Output:
// 1
// 2
// 3
// 4
// 7
// three
// 8
// 12
// 12 equals 12

在不指定等级的情况下初始化数组

int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
如果选择在不初始化的情况下声明数组变量,则必须使用运算符将数组分配给该变量。以下示例显示了 的用法
int[,] array5;
array5 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };   // OK
//array5 = {{1,2}, {3,4}, {5,6}, {7,8}};   // Error
//为特定数组元素赋值。
array5[2, 1] = 25;
//下面的示例获取特定数组元素的值并将其分配给变量
int elementValue = array5[2, 1];
//下面的代码示例将数组元素初始化为默认值
int[,] array6 = new int[10, 10];

对于多维数组,遍历元素,以便首先增加最右维的索引,然后增加下一个左维,依此类推:

int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// Or use the short form:
// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };

foreach (int i in numbers2D)
{
    System.Console.Write("{0} ", i);
}
// Output: 9 99 3 33 5 55

在下面的示例中,初始化整数的二维数组并将其传递给该方法。该方法显示数组的元素。Print2DArray

class ArrayClass2D
{
    static void Print2DArray(int[,] arr)
    {
        // Display the array elements.
        for (int i = 0; i < arr.GetLength(0); i++)
        {
            for (int j = 0; j < arr.GetLength(1); j++)
            {
                System.Console.WriteLine("Element({0},{1})={2}", i, j, arr[i, j]);
            }
        }
    }
    static void Main()
    {
        // Pass the array as an argument.
        Print2DArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
    Element(0,0)=1
    Element(0,1)=2
    Element(1,0)=3
    Element(1,1)=4
    Element(2,0)=5
    Element(2,1)=6
    Element(3,0)=7
    Element(3,1)=8
*/

交错数组

交错数组是一个数组,其元素是数组,可能具有不同的大小。交错数组有时称为“数组数组”。以下示例演示如何声明、初始化和访问交错数组。

下面是具有三个元素的一维数组的声明,每个元素都是整数的一维数组:

int[][] jaggedArray = new int[3][];
// 必须先初始化其元素,然后才能使用 。可以像这样初始化元素:jaggedArray

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

// 每个元素都是整数的一维数组。第一个元素是 5 个整数的数组,第二个元素是 4 个整数的数组,第三个元素是 2 个整数的数组。

// 也可以使用初始值设定项用值填充数组元素,在这种情况下,您不需要数组大小。例如:

jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };

可以使用以下速记形式。请注意,不能从元素初始化中省略运算符,因为元素没有默认初始化:

int[][] jaggedArray3 =
{
    new int[] { 1, 3, 5, 7, 9 },
    new int[] { 0, 2, 4, 6 },
    new int[] { 11, 22 }
};

交错数组是数组的数组,因此其元素是引用类型,并初始化为 。null

您可以访问单个数组元素,如以下示例所示:

// Assign 77 to the second element ([1]) of the first array ([0]):
jaggedArray3[0][1] = 77;

// Assign 88 to the second element ([1]) of the third array ([2]):
jaggedArray3[2][1] = 88;

可以混合交错数组和多维数组。下面是包含三个不同大小的二维数组元素的一维交错数组的声明和初始化。

int[][,] jaggedArray4 = new int[3][,]
{
    new int[,] { {1,3}, {5,7} },
    new int[,] { {0,2}, {4,6}, {8,10} },
    new int[,] { {11,22}, {99,88}, {0,9} }
};

您可以访问单个元素,如本例所示,该示例显示第一个数组的元素值(值):[1,0]5

System.Console.Write("{0}", jaggedArray4[0][1, 0]);

该方法返回交错数组中包含的数组数。例如,假设您已经声明了前一个数组,则以下行:Length

System.Console.WriteLine(jaggedArray4.Length);

此示例生成一个数组,其元素本身就是数组。每个数组元素都有不同的大小。

class ArrayTest
{
    static void Main()
    {
        // Declare the array of two elements.
        int[][] arr = new int[2][];

        // Initialize the elements.
        arr[0] = new int[5] { 1, 3, 5, 7, 9 };
        arr[1] = new int[4] { 2, 4, 6, 8 };

        // Display the array elements.
        for (int i = 0; i < arr.Length; i++)
        {
            System.Console.Write("Element({0}): ", i);

            for (int j = 0; j < arr[i].Length; j++)
            {
                System.Console.Write("{0}{1}", arr[i][j], j == (arr[i].Length - 1) ? "" : " ");
            }
            System.Console.WriteLine();
        }
        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
    Element(0): 1 3 5 7 9
    Element(1): 2 4 6 8
*/

隐式类型数组

可以创建一个隐式类型数组,其中数组实例的类型是从数组初始值设定项中指定的元素推断出来的。任何隐式类型变量的规则也适用于隐式类型数组。有关更多信息,请参见隐式类型化局部变量

隐式类型数组通常与匿名类型以及对象和集合初始值设定项一起在查询表达式中使用。

下面的示例演示如何创建隐式类型数组:

class ImplicitlyTypedArraySample
{
    static void Main()
    {
        var a = new[] { 1, 10, 100, 1000 }; // int[]
        var b = new[] { "hello", null, "world" }; // string[]

        // single-dimension jagged array
        var c = new[]
        {
            new[]{1,2,3,4},
            new[]{5,6,7,8}
        };

        // jagged array of strings
        var d = new[]
        {
            new[]{"Luca", "Mads", "Luke", "Dinesh"},
            new[]{"Karen", "Suma", "Frances"}
        };
    }
}

对象初始值设定项中的隐式类型数组

创建包含数组的匿名类型时,必须在类型的对象初始值设定项中隐式键入该数组。在下面的示例中,是匿名类型的隐式类型数组,每个数组都包含一个名为 的数组。请注意,关键字未在对象初始值设定项中使用。contactsPhoneNumbersvar

var contacts = new[]
{
    new {
        Name = " Eugene Zabokritski",
        PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
    },
    new {
        Name = " Hanying Feng",
        PhoneNumbers = new[] { "650-555-0199" }
    }
};

 

标签:Console,数组,int,WriteLine,new,array
From: https://www.cnblogs.com/tx1185498724/p/17272471.html

相关文章

  • 【LBLD】双指针技巧秒杀七道数组题目
    【LBLD】双指针技巧秒杀七道数组题目快慢指针技巧classSolution{public:intremoveDuplicates(vector<int>&nums){intfast=0;intslow=0;while(fast<nums.size()){if(nums.at(fast)!=nums.at(slow)){......
  • 可变数组
    1Arrayarray_create(intint_size);//创建数组2voidarray_free(Array*a);//回收数组3intarray_size(constArray*a);//告诉我们数组中有多少个单元可以用4int*array_at(Array*a,intindex);//访问数组某个单元5voidarray_inflate(Array*a,intmore_size);//让......
  • 数组
                ......
  • AcWing 3956. 截断数组
    给定一个长度为n的数组a1,a2,…,an。现在,要将该数组从中间截断,得到三个非空子数组。要求,三个子数组内各元素之和都相等。请问,共有多少种不同的截断方法?输入格式第......
  • 对象型数组做精准+模糊匹配
    前言通常情况后端返回的数组如果是英文的都是按照abcd这种方式进行排序,此时一般我们自己写或者组件自带的排序算法都是模糊排序,即输入B,会出现B***,**B**,之类,但是如果......
  • PHP 多维数组搜索 PHP multi dimensional array search
    array_column()返回input数组中键值为column_key的列,如果指定了可选参数index_key,那么input数组中的这一列的值将作为返回数组中对应值的键。参数input需要取出数组......
  • 数组
    数组的定义数组是相同类型的有序集合数组描述的是相同类型的若干个数据,按照一定的先后次序组合而成的每一个数据都被称为数据元素,可以通过下标来访问他们Java内存分......
  • 力扣26.删除有序数组中的重复项【顺序表】
    ......
  • 两数组的交集|哈希集
    两个数组的交集寻找两个数组相同的元素,注意返回元素的唯一性对应题目349.两个数组的交集哈希集合使用两个哈希集合,第一个保存前一个数组的元素,第二个集合遍历第二个......
  • 力扣-数组-双指针
        1classSolution(object):2defremoveElement(self,nums,val):3"""4:typenums:List[int]5:typeval:int......