Rearrange position in an array based on an index given in another array
I have two arrays as shown below.
string[] alb = new string[5]
{
"B","Z","C", "E","T"
};
int[] orderedIndexes = {0,3,4,1,2}
Based on the indices given in the second array, I would like to align the elements in the first array. I don't want to use another array as a buffer and would like to use the same array to replace elements. The result expected is similar to
alb = {"B","E","T","Z","C"}.
Note. Since the real problem has real business values, I cannot post the homework I did.
Any help would be really appreciated.
source to share
You should first check if this index array is a valid index array like this:
var isValidIndex = !Enumerable.Range(0, alb.Length - 1).Except(orderedIndexes).Any();
Then you can just use Select
in orderedIndexes
like this:
var result = orderedIndexes.Select(i => alb[i]).ToArray();
//result: {"B","E","T","Z","C"}
source to share
Linq's answer is absolutely great, but I thought it would be wise to solve it in old school array manipulation mode. Also, part of the mentioned question not creating a buffer which for me linq's answer breaks somewhat. Anyway, what is it worth ...
using System;
namespace x
{
class Program
{
static void Main()
{
var alb = new[] { "B","Z","C","E","T" };
int[] orderedIndexes = {2,0,1,4,3};
for (var i = 0; i < orderedIndexes.Length; i++)
{
var x = orderedIndexes[i];
var ts = alb[i];
alb[i] = alb[x];
alb[x] = ts;
x = Array.IndexOf(orderedIndexes, i);
var ti = orderedIndexes[i];
orderedIndexes[i] = orderedIndexes[x];
orderedIndexes[x] = ti;
}
for (var i = 0; i < orderedIndexes.Length; i++)
{
Console.WriteLine("{0}, {1}", i, alb[i]);
}
}
}
}
source to share