英文:
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 < 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.
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论