繁体   English   中英

如何在 C# 中创建 3D 列表

[英]How to create a 3D List in C#

我有一个由 2 个列表组成的列表,其中包含以下数字:list(1) = (2,3,5,3) list(2) = (1,3,9,2)。 现在我必须创建两个矩阵:第一个矩阵 4x4 应该在对角线上包含 list(1) 的所有元素,其余数字应该为零。

第二个矩阵 4x4 应该在对角线上包含 list(2) 的所有元素。 其余的数字应该为零。

我想用 for 循环来做到这一点。 请你帮助我好吗? 我不知道如何开始,我是 C# 新手,我找不到像使用 Matlab 一样清楚地说明如何使用 3D 矩阵的参考资料。 非常感谢!

为第一个列表创建一个常规List<int>

List<int> list = new List<int>() { 2, 3, 5, 3 };

然后你的'矩阵'(它实际上是一个二维数组):

int[,] matrix = new int[4, 4];

现在,对角线表示column == row ,因此使用两个循环,您只能在满足该条件时输入值。

for (int row = 0; row < list.Count; row++)
{
    for (int col = 0; col < list.Count; col++)
    {
        if (col == row)
            matrix[row, col] = list[row];
        else
            matrix[row, col] = 0;
    }
}

确认:

在此处输入图片说明

对第二个列表做同样的事情。 您可以轻松编写一个函数来执行此操作。

编辑

这里把它放到一个函数中,以及如何使用它。

static int[,] CreateMatrix(List<int> list)
{
    int[,] matrix = new int[list.Count, list.Count];

    for (int row = 0; row < list.Count; row++)
    {
        for (int col = 0; col < list.Count; col++)
        {
            if (col == row)
                matrix[row, col] = list[row];
            else
                matrix[row, col] = 0;
        }
    }

    return matrix;
}

调用:

var list1 = new List<int>() { 2, 3, 5, 3 };
var list2 = new List<int>() { 1, 3, 9, 2 };

var matrix1 = CreateMatrix(list1);
var matrix2 = CreateMatrix(list2);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM