Simple study of Array
CreateArr() creates an array and ForeachArr() iterates over the array
namespace Test
{
class Program
{
static void Main(string[] args)
{
ForeachArr(new int[] { 1, 2, 3 });
ForeachArr(new String[] { "abc", "bcd" });
}
public static void ForeachArr(Array arr)
{
for (int i = 0 ; i < arr.Length; i++)
{
Console.WriteLine(arr.GetValue(i));
}
}
public static void CreateArr()
{
//子类直接创建数组
int[] arr;
String[] arr2;
//直接用Array的方式创建数组
Array arr3 = Array.CreateInstance(typeof(String), 100);
//String[] arr3 = new String[100]
arr3.SetValue("abc", 0);
Console.WriteLine(arr3.GetValue(0));
}
}
}
Multidimensional Arrays
public static void MutipleRanksArr()
{
//两种创建二维数组的方法
//Array
Array arrArr = Array.CreateInstance(typeof(int), 5, 5);
Console.WriteLine(arrArr.GetValue(1, 1));
//子类方式
int[,] arrArr2 = new int[5, 5];
Console.WriteLine(arrArr2[1, 1]);
//多维遍历
for (int i = 0; i < arrArr2.GetLength(0); i++)
{
for (int j = 0; j < arrArr2.GetLength(1); j++)
{
Console.Write(arrArr2[i, j]);
}
Console.WriteLine();
}
}
1. Setting an array can only be read and cannot be modified.
static void Main(string[] args)
{
ReadOnlyCollection<int> read = ReadonlyArr(new int[] { 1, 2, 3 });
}
public static ReadOnlyCollection<int> ReadonlyArr(int[] arr)
{
ReadOnlyCollection<int> read = Array.AsReadOnly(arr);
Console.WriteLine(read[0]);
return read;
}
2. Sort an array
//排序
public static void SortArr()
{
String[] str = { "abc", "bcd", null, "123" };
Array.Sort(str);
ForeachArr(str);
}
3. Clear an array to prepare for the next filling.
public static void Init(int[] arr, params int[] nums)
{
Array.Clear(arr, 0, arr.Length);
//清空原集合 为填充做准备
for (int i = 0; i < nums.Length; i++)
{
arr[i] = nums[i];
}
}
4. Merge the second half of an array into another array
static void Main(string[] args)
{
Copy(new int[] { 1, 2, 3, 4, 5 }, new int[] { 6, 7, 8, 9, 10 });
}
public static void Copy(int[] src, int[] dest)
{
//为数组扩容
int oldLen = dest.Length;
Array.Resize(ref dest, dest.Length + (src.Length + 1) / 2);
//进行复制
Array.Copy(src, src.Length / 2, dest, oldLen, (src.Length + 1) / 2);
ForeachArr(dest);
}
5. Determine whether two arrays are equal
class Program
{
static void Main(string[] args)
{
Console.WriteLine(EqArr(new int[] { 1, 2 }, new int[] { 1, 2 }));
}
public static bool EqArr(int[] arr1, int[] arr2)
{
//Console.WriteLine(arr1.Equals(arr2)); //Equals支持引用相等,堆中的地址相等,但是因为引用不相等导致堆开辟两空间,因此类库不支持
if (arr1 == arr2)
{
return true;
}
else if (arr1 == null || arr2 == null)
{
return false;
}
else if (arr1.Length != arr2.Length)
{
return false;
}
else
{
for (int i = 0; i < arr1.Length; i++)
{
if (arr1[i] != arr2[i])
{
return false;
}
}
return true;
}
}
6. Reverse the array
static void Main(string[] args)
{
ReverseArr(new int[] { 5, 4, 3, 2, 1 });
}
public static void ReverseArr(int[] nums)
{
Array.Reverse(nums);
ForeachArr(nums);
}