通过索引获取数组项

5

我有两个数组,一个包含值,另一个包含索引。

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 };

现在我想要一个由选中indices数组的索引所对应的items组成的结果数组。
// 2, 7, 9, 13, 19
int[] result = new []{ items[1], items[3], items[5], items[6], items[7], items[9] }; 

问题:是否有更通用的方法?


顺便提一下,这有时也被称为“gather”,特别是在矢量化指令(AVX等)的上下文中:https://en.wikipedia.org/wiki/Vectored_I/O - Marc Gravell
4个回答

11
var results = Array.ConvertAll(indices, i => items[i]);

如果 i > items.Length 或为负数会怎样? - Lews Therin
1
@LewsTherin 如果 indices 无效,那么它会抛出(可能是 IndexOutOfRangeException),我认为这是正确的行为。 - Marc Gravell

3

尝试使用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();

1
一个好的for循环也可以完成这项工作:
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 };

List<int> resultList = new List<int>();
for (int i = 0; i < indices.Length; i++)
{
     resultList .Add(items[indices[i]]);
}

解释:

使用[ ]操作符访问indices中的特定索引时,它将返回数字。这可以再次用于索引/访问items中的特定位置。因此您具有双重索引。

编辑:

如果您需要结果作为数组,则可以使用ToArray方法进行转换:

int [] result = resultList.ToArray();

3
我建议将“results”转换为数组(如问题中所示):“int[] results = new int[indices.Length]; ... results[i] = items[indices[i]];” - Dmitry Bychenko

1
为了提供选择:
int[] result = items.Select((value, index) => new { Index = index, Value = value }) //Add indexes
                    .Where(w => indices.Contains(w.Index))                          //Filter by indexes
                    .Select(s => s.Value).ToArray();                                //Extract values to result array

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接