What is selectMany.ToArray()
method? Is it a built in method in C#
?
I need to convert two dimensional array to one dimensional array.
What is selectMany.ToArray()
method? Is it a built in method in C#
?
I need to convert two dimensional array to one dimensional array.
If you mean a jagged array (T[][]
), SelectMany
is your friend. If, however, you mean a rectangular array (T[,]
), then you can just enumerate the date data via foreach
- or:
int[,] from = new int[,] {{1,2},{3,4},{5,6}};
int[] to = from.Cast<int>().ToArray();
SelectMany is a projection operator, an extension method provided by the namespace System.Linq.
It performs a one to many element projection over a sequence, allowing you to "flatten" the resulting sequences into one.
You can use it in this way:
int[][] twoDimensional = new int[][] {
new int[] {1, 2},
new int[] {3, 4},
new int[] {5, 6}
};
int [] flattened = twoDimensional.SelectMany(x=>x).ToArray();
This solution is devoted to convert any sort of int
array, regular, jagged, or nested (these last are taken from javascript and its object notation, but they can also be implemented as complex jagged array of objects in C#), into a simple mono-dimensional integers array:
public static int[] getFlattenedIntArray(object jaggedArray)
{
var flattenedArray = new List<int>();
var jaggedArrayType = jaggedArray.GetType();
var expectedType = typeof(int);
if (jaggedArrayType.IsArray)
{
if (expectedType.IsAssignableFrom(jaggedArrayType.GetElementType()))
{
foreach (var el in jaggedArray as int[])
{
flattenedArray.Add(el);
}
}
else
{
foreach (var el in jaggedArray as object[])
{
foreach (var retIntEl in getFlattenedIntArray(el))
{
flattenedArray.Add(retIntEl);
}
}
}
}
else if (jaggedArrayType == expectedType)
{
flattenedArray.Add((int)jaggedArray);
}
else
{
return new int[0];
}
return flattenedArray.ToArray();
}
Try it with this fiddle: https://dotnetfiddle.net/5HGX96
my solution:
public struct Array3D<T>
{
public T[] flatten;
int x_len;
int y_len;
int z_len;
public Array3D(int z_len, int y_len, int x_len)
{
this.x_len = x_len;
this.y_len = y_len;
this.z_len = z_len;
flatten = new T[z_len * y_len * x_len];
}
public int getOffset(int z, int y, int x) => y_len * x_len * z + x_len * y + x;
public T this[int z, int y, int x] {
get => flatten[y_len * x_len * z + x_len * y + x];
set => flatten[y_len * x_len * z + x_len * y + x] = value;
}
public T this[int flat_index] {
get => flatten[flat_index];
set => flatten[flat_index] = value;
}
}