Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to set values in a multidimensional array using a linear index
    primarykey
    data
    text
    <p>What is the most efficient way of setting values in C# multi-dimensional arrays using a linear index? For example given an array...</p> <pre><code>int[,,] arr2 = { {{0,1,2}, {3,4,5}, {6,7,8}} , {{9,10,11}, {12,13,14}, {15,16,17}} , {{18,19,20}, {21,22,23}, {24,25,26}} }; </code></pre> <p>How do I set all the elements to 30 using a linear index ...</p> <pre><code>//This code does not work for (int i = 0; i &lt; arr.Length; i++) { arr.SetValue(30, i); } </code></pre> <p>Apparently the SetValue() above does not work with multidimensional arrays.</p> <p>Here is the best solution that I could come up with...</p> <p>EDIT: Added some clarifications to the code...</p> <pre><code>static class Program { static void Main(string[] args) { //Sample input. int[,,] arr2 = { {{0,1,2}, {3,4,5}, {6,7,8}} , {{9,10,11}, {12,13,14}, {15,16,17}} , {{18,19,20}, {21,22,23}, {24,25,26}} }; int[] arr1 = { 1, 2, 3, 4 }; setElementsTo30(arr2); setElementsTo30(arr1); } //Must be able to process int arrays of arbitrary dimensions and content private static void setElementsTo30(Array arr) { IList&lt;int&gt; cumulativeLength = getCumulativeLengths(arr); for (int i = 0; i &lt; arr.Length; i++) { SetValue(arr, i, 30, cumulativeLength); } } public static void SetValue(this Array arr, int index, object value, IList&lt;int&gt; cumulativeLength) { int[] arrayIndex = new int[arr.Rank]; for (int dim = arr.Rank-1; dim &gt;= 0; dim--) { arrayIndex[dim] = index / cumulativeLength[dim] % arr.GetLength(dim); } arr.SetValue(value, arrayIndex); } private static IList&lt;int&gt; getCumulativeLengths(Array arr) { List&lt;int&gt; lengths = new List&lt;int&gt;(arr.Rank); for (int dim = 0; dim &lt; arr.Rank; dim++) { int prod = 1; for (int i = dim + 1; i &lt; arr.Rank; i++) { prod *= arr.GetLength(i); } lengths.Add(prod); } return (IList&lt;int&gt;)lengths; } } </code></pre> <p>Is there a way to do the same more efficiently and possibly using something provided by the framework itself (i.e. something which can be used without much hassle.)</p> <p>Thanks,<br> SDX2000.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload