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

如何通过索引数组提取元素数组元素?通用实现方案问询

通用提取数组指定索引元素的实现方式

当然有更通用的实现方式啦!手动挨个写索引取值确实能解决眼前的问题,但要是indices数组长度变了、或者需要在别的地方复用这个逻辑,这种写法就太麻烦了。下面给你分享几种C#里常用的通用方案:

LINQ 简洁实现

这是最常用也最简洁的方式,借助LINQ的Select方法就能一行搞定:

using System.Linq;

int[] items = { 1, 2, 3, 7, 8, 9, 13, 16, 19, 23, 25, 26, 29, 31, 35, 36, 39, 45 };
int[] indices = { 1, 3, 5, 6, 7, 9 };
int[] result = indices.Select(index => items[index]).ToArray();

这种写法完全通用——不管indices的长度怎么变化,代码都不用修改,只要保证索引值在items的有效范围内就行。

手动循环实现

如果不想依赖LINQ,手动循环的方式也很清晰,而且不引入额外依赖:

int[] items = { 1, 2, 3, 7, 8, 9, 13, 16, 19, 23, 25, 26, 29, 31, 35, 36, 39, 45 };
int[] indices = { 1, 3, 5, 6, 7, 9 };
int[] result = new int[indices.Length];

for (int i = 0; i < indices.Length; i++)
{
    result[i] = items[indices[i]];
}

逻辑一目了然,同样适配任意长度的indices数组。

额外注意事项

不管用哪种方式,都要留意索引越界的问题——如果indices里的某个值小于0或者大于等于items.Length,程序会抛出IndexOutOfRangeException。如果需要处理这种异常情况,可以在取值前加个判断,比如LINQ版本可以这么改:

int[] result = indices
    .Where(index => index >= 0 && index < items.Length)
    .Select(index => items[index])
    .ToArray();

这样就能自动过滤掉无效的索引,避免报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:03:09