2009-07-25 16 views

答えて

2

私はちょうど私が使用するこのコードを書いた:

using System.Collections.Generic; 
using System.Collections.ObjectModel; 
using System.Linq; 

namespace MiscellaneousUtilities 
{ 
    public static class Enumerable 
    { 
     public static T[,] ToRow<T>(this IEnumerable<T> target) 
     { 
      var array = target.ToArray(); 
      var output = new T[1, array.Length]; 
      foreach (var i in System.Linq.Enumerable.Range(0, array.Length)) 
      { 
       output[0, i] = array[i]; 
      } 
      return output; 
     } 

     public static T[,] ToColumn<T>(this IEnumerable<T> target) 
     { 
      var array = target.ToArray(); 
      var output = new T[array.Length, 1]; 
      foreach (var i in System.Linq.Enumerable.Range(0, array.Length)) 
      { 
       output[i, 0] = array[i]; 
      } 
      return output; 
     } 
    } 
} 
+0

@alexw良いキャッチ。以前のコメントを削除します。 – shoelzer

8

は直接的な方法はありません。ものをdouble[,]にコピーする必要があります。仮定すると、あなたはそれが一列にしたい:

double[,] arr = new double[1, original.Length]; 
for (int i = 0; i < original.Length; ++i) 
    arr[0, i] = original[i]; 
+0

@alexw良いキャッチ。以前のコメントを削除します。 – shoelzer

0

Mehrdadは、それ自体で1次元配列から幅または高さのいずれかを決定するための現実的な方法はありませんので、幅が1であることを前提としています。あなたは「幅」の一部(外)という概念を持っている場合は、Mehrdadのコードは次のようになります。

行の主要なは、おそらく多くのアプリケーション(行列、テキスト・バッファまたはグラフィックス)でより一般的である

// assuming you have a variable with the 'width', pulled out of a rabbit's hat 
int height = original.Length/width; 
double[,] arr = new double[width, height]; 
int x = 0; 
int y = 0; 
for (int i = 0; i < original.Length; ++i) 
{ 
    arr[x, y] = original[i]; 
    x++; 
    if (x == width) 
    { 
     x = 0; 
     y++; 
    } 
} 

、が、

// assuming you have a variable with the 'width', pulled out of a rabbit's hat 
int height = original.Length/width; 
double[,] arr = new double[height, width]; // note the swap 
int x = 0; 
int y = 0; 
for (int i = 0; i < original.Length; ++i) 
{ 
    arr[y, x] = original[i]; // note the swap 
    x++; 
    if (x == width) 
    { 
     x = 0; 
     y++; 
    } 
} 
4

あなたは2次元配列の幅を知っている場合は、VALUを置くために、次を使用することができます1つの行として別々に表示されます。

private T[,] toRectangular<T>(T[] flatArray, int width) 
    { 
     int height = (int)Math.Ceiling(flatArray.Length/(double)width); 
     T[,] result = new T[height, width]; 
     int rowIndex, colIndex; 

     for (int index = 0; index < flatArray.Length; index++) 
     { 
      rowIndex = index/width; 
      colIndex = index % width; 
      result[rowIndex, colIndex] = flatArray[index]; 
     } 
     return result; 
    } 
+1

非常に簡単ですが、(比較的)計算上高価です。 – cjbarth

+0

Jon Skeetは、パフォーマンス重視の方法をhttp://stackoverflow.com/questions/5132397/fast-way-to-convert-a-two-dimensional-array-to-a-list-one-dimensionalに掲載しました。 – ShawnFeatherly