C#中操作数组的推荐方式是使用多个索引吗?

huangapple go评论122阅读模式
英文:

What's the recommended way to operate on C# arrays by multiple indexes?

问题

array2=array1[idx];
但据我所知,C#中的[]索引仅适用于单个元素查询。那么,建议的方法是什么呢?

英文:

Let's say that I have two arrays:

double[] array1 =  new double [] {22.5, 15, 33.7, 42, 17, 7.5, 3.5, 1, 17.5, 7.7, 5}
int[] idx = new int[] { 1, 4, 5, 8};

Now I need to generate new array that will have values from array1, but only this with indexes matching idx. So, in this case it should be:

{15, 17, 7.5, 17.5}

I'm more experienced in MATLAB and I was expecting that I can do simple:

array2=array1[idx];

But as far as I found the C# [] indexing works only for one element queries. So, what is recommended way to do this?

答案1

得分: 4

以下是翻译好的部分:

Well you could do it "long-hand":

double[] array2 = new double[idx.Length];
for (int i = 0; i < idx.Length; i++)
{
    array2[i] = array1[idx[i]];
}

Or use LINQ:

double[] array2 = idx.Select(i => array1[i]).ToArray();

Both will do the job. There's no "shortcut" available. You could potentially create your own class to do custom indexing if you really wanted to, but I'd just use one of the approaches above.

英文:

Well you could do it "long-hand":

double[] array2 = new double[idx.Length];
for (int i = 0; i &lt; idx.Length; i++)
{
    array2[i] = array1[idx[i]];
}

Or use LINQ:

double[] array2 = idx.Select(i =&gt; array1[i]).ToArray();

Both will do the job. There's no "shortcut" available. You could potentially create your own class to do custom indexing if you really wanted to, but I'd just use one of the approaches above.

答案2

得分: -1

你可以使用 LINQ 的 Enumerable.Where 方法,结合 System.Array 类的 Contains 方法,来实现相同的功能。

英文:

You can use LINQ's Enumerable.Where method in combination with the Contains method of the System.Array class to achieve the same functionality.

huangapple
  • 本文由 发表于 2023年2月26日 22:25:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572643.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定