数组操作 #

一、Array类概述 #

Array类是所有数组的基类,提供了丰富的数组操作方法。

1.1 常用属性 #

csharp
int[] numbers = { 1, 2, 3, 4, 5 };

int length = numbers.Length;
int rank = numbers.Rank;
bool isReadOnly = numbers.IsReadOnly;
bool isFixedSize = numbers.IsFixedSize;
bool isSynchronized = numbers.IsSynchronized;

1.2 常用方法 #

方法 说明
Sort 排序
Reverse 反转
Find 查找元素
FindAll 查找所有匹配元素
IndexOf 查找索引
Copy 复制
Clear 清空
Resize 调整大小

二、排序 #

2.1 基本排序 #

csharp
int[] numbers = { 5, 2, 8, 1, 9, 3 };
Array.Sort(numbers);

foreach (int n in numbers)
{
    Console.Write($"{n} ");
}

2.2 部分排序 #

csharp
int[] numbers = { 5, 2, 8, 1, 9, 3 };
Array.Sort(numbers, 1, 4);

2.3 自定义比较器 #

csharp
string[] names = { "张三", "李四", "王五", "赵六" };

Array.Sort(names, (a, b) => a.Length.CompareTo(b.Length));

Array.Sort(names, StringComparer.OrdinalIgnoreCase);

2.4 降序排序 #

csharp
int[] numbers = { 5, 2, 8, 1, 9, 3 };
Array.Sort(numbers);
Array.Reverse(numbers);

int[] numbers2 = { 5, 2, 8, 1, 9, 3 };
Array.Sort(numbers2, (a, b) => b.CompareTo(a));

2.5 对象数组排序 #

csharp
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

var people = new Person[]
{
    new Person { Name = "张三", Age = 25 },
    new Person { Name = "李四", Age = 30 },
    new Person { Name = "王五", Age = 20 }
};

Array.Sort(people, (a, b) => a.Age.CompareTo(b.Age));

Array.Sort(people, (a, b) => string.Compare(a.Name, b.Name));

三、查找 #

3.1 IndexOf和LastIndexOf #

csharp
int[] numbers = { 1, 2, 3, 2, 4, 2, 5 };

int first = Array.IndexOf(numbers, 2);
int last = Array.LastIndexOf(numbers, 2);
int notFound = Array.IndexOf(numbers, 10);

3.2 Find和FindLast #

csharp
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int firstEven = Array.Find(numbers, n => n % 2 == 0);
int lastEven = Array.FindLast(numbers, n => n % 2 == 0);

3.3 FindAll #

csharp
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int[] evens = Array.FindAll(numbers, n => n % 2 == 0);
int[] greaterThan5 = Array.FindAll(numbers, n => n > 5);

3.4 FindIndex和FindLastIndex #

csharp
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int firstEvenIndex = Array.FindIndex(numbers, n => n % 2 == 0);
int lastEvenIndex = Array.FindLastIndex(numbers, n => n % 2 == 0);

3.5 Exists和TrueForAll #

csharp
int[] numbers = { 1, 2, 3, 4, 5 };

bool hasEven = Array.Exists(numbers, n => n % 2 == 0);
bool allPositive = Array.TrueForAll(numbers, n => n > 0);

3.6 BinarySearch #

csharp
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int index = Array.BinarySearch(numbers, 5);

if (index >= 0)
    Console.WriteLine($"找到元素,索引:{index}");
else
    Console.WriteLine("未找到元素");

四、复制 #

4.1 Copy #

csharp
int[] source = { 1, 2, 3, 4, 5 };
int[] destination = new int[5];

Array.Copy(source, destination, source.Length);

Array.Copy(source, 1, destination, 0, 3);

4.2 CopyTo #

csharp
int[] source = { 1, 2, 3, 4, 5 };
int[] destination = new int[10];

source.CopyTo(destination, 0);
source.CopyTo(destination, 5);

4.3 Clone #

csharp
int[] original = { 1, 2, 3, 4, 5 };
int[] copy = (int[])original.Clone();

4.4 ConstrainedCopy #

csharp
int[] source = { 1, 2, 3, 4, 5 };
int[] destination = new int[5];

bool success = Array.ConstrainedCopy(source, 0, destination, 0, 5);

五、反转与清空 #

5.1 Reverse #

csharp
int[] numbers = { 1, 2, 3, 4, 5 };
Array.Reverse(numbers);

Array.Reverse(numbers, 1, 3);

5.2 Clear #

csharp
int[] numbers = { 1, 2, 3, 4, 5 };
Array.Clear(numbers, 0, numbers.Length);

Array.Clear(numbers, 1, 2);

六、调整大小 #

6.1 Resize #

csharp
int[] numbers = { 1, 2, 3 };
Array.Resize(ref numbers, 5);
Array.Resize(ref numbers, 2);

6.2 扩展数组 #

csharp
public static T[] Append<T>(T[] array, T item)
{
    Array.Resize(ref array, array.Length + 1);
    array[array.Length - 1] = item;
    return array;
}

七、转换 #

7.1 ConvertAll #

csharp
string[] numbers = { "1", "2", "3", "4", "5" };
int[] ints = Array.ConvertAll(numbers, int.Parse);

int[] numbers = { 1, 2, 3, 4, 5 };
string[] strings = Array.ConvertAll(numbers, n => n.ToString());

7.2 ForEach #

csharp
int[] numbers = { 1, 2, 3, 4, 5 };
Array.ForEach(numbers, n => Console.WriteLine(n));

八、实战示例 #

8.1 数组去重 #

csharp
public static T[] Distinct<T>(T[] array)
{
    var result = new List<T>();
    foreach (var item in array)
    {
        if (!result.Contains(item))
            result.Add(item);
    }
    return result.ToArray();
}

public static T[] Distinct<T>(T[] array)
{
    return array.Distinct().ToArray();
}

8.2 数组合并 #

csharp
public static T[] Merge<T>(T[] first, T[] second)
{
    var result = new T[first.Length + second.Length];
    Array.Copy(first, 0, result, 0, first.Length);
    Array.Copy(second, 0, result, first.Length, second.Length);
    return result;
}

8.3 数组切片 #

csharp
public static T[] Slice<T>(T[] array, int start, int length)
{
    var result = new T[length];
    Array.Copy(array, start, result, 0, length);
    return result;
}

8.4 数组统计 #

csharp
public static (int Min, int Max, double Average, int Sum) Analyze(int[] array)
{
    if (array == null || array.Length == 0)
        throw new ArgumentException("数组不能为空");
    
    int min = array[0];
    int max = array[0];
    int sum = 0;
    
    foreach (int n in array)
    {
        if (n < min) min = n;
        if (n > max) max = n;
        sum += n;
    }
    
    return (min, max, (double)sum / array.Length, sum);
}

8.5 移动元素 #

csharp
public static void RotateLeft<T>(T[] array, int positions)
{
    positions = positions % array.Length;
    T[] temp = new T[positions];
    Array.Copy(array, temp, positions);
    Array.Copy(array, positions, array, 0, array.Length - positions);
    Array.Copy(temp, 0, array, array.Length - positions, positions);
}

public static void RotateRight<T>(T[] array, int positions)
{
    positions = positions % array.Length;
    RotateLeft(array, array.Length - positions);
}

九、总结 #

数组操作要点:

方法 说明
Sort 排序
Reverse 反转
Find/FindAll 查找
IndexOf 查找索引
Copy 复制
Clear 清空
Resize 调整大小
ConvertAll 类型转换

下一步,让我们学习集合框架!

最后更新:2026-03-26