2014-02-26 41 views
0

到列表轉換爲數組[,]有代碼:轉換列表contaning列表<double>單挑扁平化陣列

double[,] arr = new double[list.Count, list[0].Length]; 
for (int i = 0; i < list.Count; i++) 
{ 
    for (int j = 0; j < list[0].Length; j++) 
    { 
     arr[i, j] = list[i][j]; 
    } 
} 

我想將它轉化成扁平陣列所以使用的事實

Flattened array index computation 

array[(Y coordinate * width) + X coordinate] 

2D array index computation 

array[Y coordinate, X coordinate] 

代碼更改

double[] arr = new double[list.Count * list[0].Length]; 
for (int i = 0; i < list.Count ; i++) 
{ 
    for (int j = 0; j < list[0].Length; j++) 
    { 
      arr[i] = list[i * list[0].Length + j]; 
    } 

} 

但什麼是代碼爲List < List <double> >轉換FL數組陣列? 作爲上述代碼,可以在2個循環中完成嗎?

List<List<double>>表示double[,] arr

+0

不應'ARR [I] =列表[I *列表[0]。長度+ D];'是'arr [i * list [0] .Length + j] = list [i] [j];'? – CompuChip

+0

如果要將列表的列表轉換爲多維數組,那不是「扁平化」。展平列表將導致一維數組。 – dcastro

回答

1

在循環(即,沒有LINQ)會是這樣的

public static void Main() 
{ 
    List<List<double>> listOfLists = new List<List<double>>(); 

    listOfLists.Add(new List<double>() { 1, 2, 3 }); 
    listOfLists.Add(new List<double>() { 4, 6 }); 

    int flatLength = 0; 
    foreach (List<double> list in listOfLists) 
     flatLength += list.Count; 

    double[] flattened = new double[flatLength]; 

    int iFlat = 0; 

    foreach (List<double> list in listOfLists) 
     foreach (double d in list) 
      flattened[iFlat++] = d; 

    foreach (double d in flattened) 
     Console.Write("{0} ", d); 

    Console.ReadLine(); 
} 
2

老實說,我不是100%肯定你問什麼,但拼合一個List<List<>>可以使用SelectMany從LINQ的,這裏有一個簡單的例子:

static void Main(string[] args) 
    { 
     var first = new List<double> {1, 2, 3}; 
     var second = new List<double> { 3, 4, 5 }; 

     var lists = new List<List<double>> {first, second}; 

     var flatten = lists.SelectMany(a => a).ToArray(); 

     foreach (var i in flatten) 
     { 
      Console.WriteLine(i); 
     } 
    } 
+0

該查詢將如何進入for循環? – cMinor

2

鑑於你的列表是一個嵌套的枚舉,你可以簡單地使用Linq。

double[] array = nestedList.SelectMany(a => a).ToArray();