【问题标题】:Accessing single-dimensional array entries with index array使用索引数组访问一维数组条目
【发布时间】:2014-03-08 04:47:27
【问题描述】:

我正在尝试通过另一个包含我希望提取的索引的数组来访问一维“数据”数组(字符串或双精度)中的元素:

string[] myWords = {"foo", "overflow", "bar", "stack"};
int[] indices = {3, 1};

string[] someWords = myWords[indices]; // Extract entries number three and one.

编译器拒绝最后一行。我想看的是someWords == {"stack", "overflow"}。

据我所知,这在 Matlab 和 Fortran 中有效,那么对于 C# 中的数组,有什么好的和优雅的方法吗?列表也很好。

this question 中的Array.GetValue(int[]) 在我的情况下不起作用,因为此方法仅适用于多维数组。`

【问题讨论】:

  • 这看起来像是可以在不同范式的语言中工作的语法。在 C# 中,数组操作更加手动; LINQ 答案是有效的(一个做这项工作的库),或者您可以将它显式地实现为 indices 中的值的循环,并使用包含结果的手动构造的数组。
  • 我当然可以手动完成,但我特别想找一个优雅的单线。
  • 我不确定“优雅的单线”是否矛盾:)。

标签: c# arrays indices


【解决方案1】:

如果你可以使用 LINQ,这里有一个方法:

string[] someWords = indices.Select(index => myWords[index]).ToArray();

【讨论】:

  • 谢谢,这看起来和我要找的东西一模一样!我一回到代码就会尝试。
【解决方案2】:

不确定这是您要问的问题。

string[] myWords = {"foo", "overflow", "bar", "stack"};
int[] indices = {3, 1};
string[] someWords = indices.Select(x=> myWords[x]).ToArray();

【讨论】:

    猜你喜欢
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    相关资源
    最近更新 更多