List<double[,]>中的问题

4
这是C# 3.0中的错误写法:
List<double> x = new List<double> { 0.0330, -0.6463, 0.1226, -0.3304, 0.4764, -0.4159, 0.4209, -0.4070, -0.2090, -0.2718, -0.2240, -0.1275, -0.0810, 0.0349, -0.5067, 0.0094, -0.4404, -0.1212 };
List<double> y = new List<double> { 0.4807, -3.7070, -4.5582, -11.2126, -0.7733, 3.7269, 2.7672, 8.3333, 4.7023,0,0,0,0,0,0,0,0,0 };

List<double[,]> z = new List<double[,]>{x,y}; // this line

产生的错误是:
Error: Argument '1': cannot convert from 'System.Collections.Generic.List<double>' to 'double[*,*]' 

需要帮助。


1
你想做什么并不清楚。你想要一个 List<List<double>> 吗?还是一个 List<double[,]> - Mike Two
错误信息很准确,您正在尝试将双精度列表转换为双精度二维数组。问题是什么? - Lasse V. Karlsen
5个回答

1
var z = new List<List<double>> { x, y };

然而,如果你想要将两个列表存储在一个二维数组([,])中(这是你的答案)。你需要手动进行转换,如下所示:

public static T[,] To2dArray(this List<List<T>> list)
{
    if (list.Count == 0 || list[0].Count == 0)
        throw new ArgumentException("The list must have non-zero dimensions.");

    var result = new T[list.Count, list[0].Count];
    for(int i = 0; i < list.Count; i++)
    {
        for(int j = 0; j < list.Count; j++)
        {
            if (list[i].Count != list[0].Count)
                throw new InvalidOperationException("The list cannot contain elements (lists) of different sizes.");
            result[i, j] = list[i][j];
        }
    }

    return result;
}

0
你是想要类似这样的东西吗?
        List<double> x = new List<double> { 0.0330, -0.6463, 0.1226, -0.3304, 0.4764, -0.4159, 0.4209, -0.4070, -0.2090, -0.2718, -0.2240, -0.1275, -0.0810, 0.0349, -0.5067, 0.0094, -0.4404, -0.1212 };
        List<double> y = new List<double> { 0.4807, -3.7070, -4.5582, -11.2126, -0.7733, 3.7269, 2.7672, 8.3333, 4.7023, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

        List<double[]> z = x.Select((x1, index) => new double[2] {x1, y[index]} ).ToList();

编辑:更改我的答案以正确地在索引上连接列表,而不是查找它。


0

这不应该是:

List<List<double>,List<double>> z = new List<List<double>, List<double>>{x,y};

但我认为那并不是你真正想要的,对吧?


0

double[,] 定义了一个多维数组,但您正在指定两个列表。

从您的初始化中看来,您正在寻找类似以下内容的东西

List<PointF> list = new List<PointF> { new PointF (0.0330F, 0.4807F), new PointF (-0.6463F, -3.7070F) };

0

List<double[,]> 的集合初始化器期望类型为 double[,](即类似于矩阵的二维数组)的元素,但您正在传递类型为 List<double>xy,这意味着它正在尝试将两个双精度浮点数列表添加为新列表的元素。

如果您要将坐标添加到列表中,则需要某种结构来包含它们。您可以编写自己的结构,也可以使用 System.Drawing.PointF


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接