You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中根据另一个数组的排序结果对数组排序?

C#中按关联数组排序的实现方案

你可以通过将两个数组的对应元素绑定后排序,再提取目标数组元素的方式实现需求,以下是几种常用的实现方法:

方法一:使用LINQ和元组快速实现

这种方式代码简洁,适合简单场景:

首先定义原始数组:

int[] array1 = { 902, 109, 205, 187, 440, 508 };
string[] array2 = { "Ford", "Opel", "Kia", "Renault", "BMW", "Toyota" };

然后通过LINQ完成配对、排序、提取:

// 配对两个数组元素,按array1的值升序排序,再提取array2的元素
var sortedPairs = array1.Zip(array2, (number, text) => (Number: number, Text: text))
                        .OrderBy(pair => pair.Number);

string[] array2Sorted = sortedPairs.Select(pair => pair.Text).ToArray();

方法二:使用自定义类(适合复杂业务场景)

如果需要更清晰的结构或后续扩展,可以定义自定义类来存储关联元素:

  1. 定义配对类:
public class ItemPair
{
    public int Number { get; set; }
    public string Text { get; set; }
}
  1. 构建配对集合并排序:
// 初始化配对列表
List<ItemPair> itemPairs = new List<ItemPair>();
for (int i = 0; i < array1.Length; i++)
{
    itemPairs.Add(new ItemPair { Number = array1[i], Text = array2[i] });
}

// 按Number字段升序排序
itemPairs.Sort((a, b) => a.Number.CompareTo(b.Number));

// 提取排序后的文本到目标数组
string[] array2Sorted = itemPairs.Select(item => item.Text).ToArray();

方法三:手动处理索引排序(不依赖LINQ)

如果不想使用LINQ,可以通过排序索引的方式实现:

// 生成索引数组,并按array1对应位置的值升序排序
int[] sortedIndices = Enumerable.Range(0, array1.Length)
                                .OrderBy(index => array1[index])
                                .ToArray();

// 根据排序后的索引构建目标数组
string[] array2Sorted = new string[array2.Length];
for (int i = 0; i < sortedIndices.Length; i++)
{
    array2Sorted[i] = array2[sortedIndices[i]];
}

验证结果

最终array2Sorted的内容为:["Opel", "Renault", "Kia", "BMW", "Toyota", "Ford"],完全符合你要求的排序规则。

内容的提问来源于stack exchange,提问作者Mdarende

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 04:33:37