将包含List <double>的List转换为单个展平数组</double>

时间:2014-02-26 14:24:49

标签: c# arrays list

将列表转换为数组[,]有代码:

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];
    }
}

我想将它转换为flatten数组,因此使用事实

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 > >转换为flatten数组的代码是什么? 是否可以像上面的代码一样在2个循环中进行?

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

3 个答案:

答案 0 :(得分:2)

老实说,我并不是百分之百确定你在问什么,但为了平展一个List<List<>>你可以使用Linq的SelectMany,这是一个简单的例子:

    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);
        }
    }

答案 1 :(得分:2)

鉴于您的列表是嵌套的可枚举,您只需使用Linq。

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

答案 2 :(得分: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();
}