.NET教程 - 数组(Array)
更新记录
转载请注明出处:
2022年9月29日 发布。
2022年9月28日 从笔记迁移到博客。
System.Array
说明
Array类型是所有一维和多维数组的基类
System.Array类型实现了IList
注意:如果需要大小可以变化的类型,考虑使用List
数组都是System.Array类的实例
数组类型(Types of Arrays)
- Single dimensional array
- Multi-dimensional array
the multi-dimensional arrays are of two types
- Jagged array: Whose rows and columns are not equal
- Rectangular array: Whose rows and columns are equal
数组的长度和秩(Length and Rank)
可以使用以下数组实例方法和属性来获得数组的长度和秩
public int GetLength (int dimension);
public long GetLongLength (int dimension);
public int Length { get; }
public long LongLength { get; }
public int GetLowerBound (int dimension);
public int GetUpperBound (int dimension);
public int Rank { get; } // Returns number of dimensions in array
数组查询(Array Searching)
数组支持以下查询:
二分查找(BinarySearch methods)
For rapidly searching a sorted array for a particular item
查找索引(IndexOf/LastIndex methods)
For searching unsorted arrays for a particular item
查找元素(Find/FindLast/FindIndex/FindLastIndex/FindAll/Exists/TrueForAll)
For searching unsorted arrays for item(s) that satisfy a given Predicate
说明:一般情况下,没有查找到元素不会抛出异常,会返回-1/Null
数组查找
Array类型注意
注意:
数值的二分查找(binary search)只能在已经排序的数组上执行
数值的二分查找方法还可以接受IComparer or IComparer
使用Array.Find方法+方法 查找元素
static void Main()
{
string[] names = { "Rodney", "Jack", "Jill" };
string match = Array.Find (names, ContainsA);
Console.WriteLine (match); // Jack
}
static bool ContainsA (string name) { return name.Contains ("a"); }
使用Array.Find方法+匿名方法 查找元素
string[] names = { "Rodney", "Jack", "Jill" };
string match = Array.Find (names, delegate (string name)
{ return name.Contains ("a"); } );
使用Array.Find方法+Lambda表达式 查找元素
string[] names = { "Rodney", "Jack", "Jill" };
string match = Array.Find (names, n => n.Contains ("a")); // Jack
数组排序(Sorting)
数组排序的主要方法:
// For sorting a single array:
public static void Sort<T> (T[] array);
public static void Sort (Array array);
// For sorting a pair of arrays:
public static void Sort<TKey,TValue> (TKey[] keys, TValue[] items);
public static void Sort (Array keys, Array items);
int index // Starting index at which to begin sorting
int length // Number of elements to sort
IComparer<T> comparer // Object making ordering decisions
Comparison<T> comparison // Delegate making ordering decisions
实例:最简单的排序
int[] numbers = { 3, 2, 1 };
Array.Sort (numbers); // Array is now { 1, 2, 3 }
实例:以第一个数组的下标来排序第二个数组
int[] numbers = { 3, 2, 1 };
string[] words = { "three", "two", "one" };
Array.Sort (numbers, words);
// numbers array is now { 1, 2, 3 }
// words array is now { "one", "two", "three" }
实例:将奇数排在前面
int[] numbers = { 1, 2, 3, 4, 5 };
Array.Sort (numbers, (x, y) => x % 2 == y % 2 ? 0 : x % 2 == 1 ? -1 : 1);
// numbers array is now { 1, 3, 5, 2, 4 }
数组反序(Reversing Elements)
预定义静态方法
public static void Reverse (Array array);
public static void Reverse (Array array, int index, int length);
实例:全部元素进行倒序
string[] pandaTest = new string[] { "Panda666", "Dog222" };
Array.Reverse(pandaTest);
foreach (string item in pandaTest)
{
Console.WriteLine(item);
}
实例:部分元素进行倒序
string[] pandaTest = new string[] { "Test1", "Test2", "Test3" };
Array.Reverse(pandaTest, 1, 2);
foreach (string item in pandaTest)
{
Console.WriteLine(item);
}
数组复制(Copying)
主要有4个方法:
实例方法:
Clone, CopyTo
静态方法:
Copy, ConstrainedCopy
说明:ConstrainedCopy表示要么复制全部成功,要么回滚
实例:原子复制数组
string[] pandaTest = new string[] { "Panda666" };
string[] des = new string[1];
Array.ConstrainedCopy(pandaTest, 0, des, 0, pandaTest.Length);
foreach (string item in des)
{
Console.WriteLine(item);
}
转为不可变类型(只读类型)
使用Array.AsReadonly()方法
实例:使用Array.AsReadonly()方法
using System.Collections.ObjectModel;
string[] pandaTest = new string[] { "Panda666" };
ReadOnlyCollection<string> readOnlyCollection = Array.AsReadOnly(pandaTest);
foreach (string item in readOnlyCollection)
{
Console.WriteLine(item);
}
数组转换和大小调整(Converting and Resizing)
数组转换:
使用Array.ConvertAll方法进行数组类型转换
使用LINQ进行数组类型转换
数组大小:
使用Resize方法进行数组大小转换
实例:使用Array.ConvertAll进行数组类型转换
float[] reals = { 1.3f, 1.5f, 1.8f };
int[] wholes = Array.ConvertAll (reals, r => Convert.ToInt32 (r));
// wholes array is { 1, 2, 2 }
实例:使用LINQ进行类型转换
string[] pandaTest = new string[] { "Panda" };
var result = from item in pandaTest
select item[0];
foreach (char item in result)
{
Console.WriteLine(item);
}
实例:使用Resize进行数组大小转换
string[] pandaTest = new string[] { "panda666" };
Array.Resize(ref pandaTest, 666);
//输出长度
Console.WriteLine(pandaTest.Count()); //666
实例
动态创建数组
Array a = Array.CreateInstance(typeof(string), 2);
a.SetValue("hi", 0); // → a[0] = "hi";
a.SetValue("there", 1); // → a[1] = "there";
string s = (string)a.GetValue(0); // → s = a[0];
//转为固定的数组
string[] cSharpArray = (string[])a;
string s2 = cSharpArray[0];
动态创建数组
Array instance = Array.CreateInstance(typeof(int),20);
//赋值
for (int i = 0; i < instance.Length; i++)
{
instance.SetValue(i+1,i);
}
//读值
for (int i = 0; i < instance.Length; i++)
{
Console.WriteLine(instance.GetValue(i));
}
//转为具体类型数组
int[] newArray = (int[])instance;
克隆数组(浅复制)
int[] arr = { 1, 2, 3, 4, 5};
//克隆
int[] newArr = (int[])arr.Clone();
克隆数组(浅复制)
string[] test1 = new string[3] { "Panda", "Dog", "Cat" };
string[] test2 = (string[])test1.Clone();
foreach (string item in test2)
{
Console.WriteLine(item);
}
数组深拷贝(一层)
string[] test1 = new string[] { "Panda", "Cat", "Monkey" };
string[] test2 = new string[test1.Length];
for (int i = 0; i < test1.Length; i++)
{
//检测是否值类型
if (test1[i] is ValueType)
{
test2[i] = test1[i];
}
else
{
test2[i] = (string)test1[i].Clone();
}
}
//修改Test2做测试
test2[0] = "Panda666";
foreach (string item in test2)
{
Console.WriteLine(item);
}
Console.WriteLine("================================");
foreach (string item in test1)
{
Console.WriteLine(item);
}
获得第一个元素和最后一个元素
int[] myArray = { 1, 2, 3 };
int first = myArray [0];
int last = myArray [myArray.Length - 1];
使用foreach遍历数组
int[] myArray = { 1, 2, 3 };
foreach (int val in myArray)
{
Console.WriteLine (val);
}
使用Array.ForEach静态方法遍历数组
Array.ForEach (new[] { 1, 2, 3 }, Console.WriteLine);
数组排序
使用Array.Sort静态方法
注意:数组的元素必须实现IComparable接口
注意:预定义基本类型都已经实现了该接口
注意:Array.Sort静态方法使用QuickSort
using System;
namespace Test
{
class PandaTest
{
public static void Main()
{
int[] arr = { 1, 3, 2, 4, 5};
Array.Sort(arr);
foreach (var item in arr)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
}
自定义排序
using System;
namespace Test
{
/// <summary>
/// 测试使用的员工类型
/// </summary>
class Employee:IComparable<Employee>
{
/// <summary>
/// 工资,按工资从高到低排序
/// </summary>
public decimal Salary { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
public Employee(string name, decimal salary)
{
this.Name = name;
this.Salary = salary;
}
/// <summary>
/// 自定义排序
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public int CompareTo(Employee other)
{
if(this.Salary < other.Salary)
{
return 1;
}
else
{
return 0;
}
}
}
class PandaTest
{
public static void Main()
{
Employee[] employees =
{
new Employee("Panda",666),
new Employee("Dog",888),
new Employee("Cat",999)
};
Array.Sort(employees);
foreach (var item in employees)
{
Console.WriteLine(item.Name + " " + item.Salary.ToString());
}
Console.ReadKey();
}
}
}
数组池
当应用经常创建和释放数组,可以使用数组池提高效率
ArrayPool
本文来自博客园,作者:重庆熊猫,转载请注明原文链接:https://www.cnblogs.com/cqpanda/p/16736859.html