C#for二维列表循环 [英] C# for loop of two dimensional List

查看:130
本文介绍了C#for二维列表循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List<List<double>> A = new List<List<double>>()
{
    new List<double>() { 1, 0, 0 },
    new List<double>() { 1, -1, 0 }
};

List<List<double>> Temm = new List<List<double>>();
for (int i = 0; i < A.Count; i++)
{
     for (int j = 0; j < A[i].Count; j++)
     {
         if (A[i][j] != 0) 
         {
             Temm[i][j] = A[i][j]; 
         }
         else 
         { 
             Temm[i][j] = Temm[i][j - 1]; }
         }
     }
}

这个double for循环有问题,我认为Temm[i][j]可能是非法的,那么正确的方法是什么?我还想知道如何声明二维List的给定大小

There is something wrong with this double for loop, I think Temm[i][j] maybe illegal, so what's the correct way ? I also wanted to know how to declare the given size of the two dimensional List

List<List<double>> Temm = new List<List<double>>

Z * Y?

推荐答案

您有2个问题.

  1. 当您第一次开始循环遍历内部循环时,应在输出集合中的那个位置初始化循环.
  2. 当您尝试访问[i] [j]-尚不存在的目录-每次都将失败.而是使用Insert方法:

List<List<double>> A = new List<List<double>>()
{
    new List<double>() { 1, 0, 0 },
    new List<double>() { 1, -1, 0 }
};    

List<List<double>> Temm = new List<List<double>>(A.Count);
for (int i = 0; i < A.Count; i++)
{
    Temm.Insert(i,new List<double>());
    for (int j = 0; j < A[i].Count; j++)
    {
        if (A[i][j] != 0) { Temm[i].Insert(j,A[i][j]); }
        else { Temm[i].Insert(j,Temm[i][j - 1]); }
    }
}

因为每次插入列表的末尾,我都希望使用Add:

Because each time you insert to the end of the list I would prefer to use the Add:

List<List<double>> B = new List<List<double>>();
for (int i = 0; i < A.Count; i++)
{
    List<double> innerResult = new List<double>();
    for (int j = 0; j < A[i].Count; j++)
    {
        if (A[i][j] != 0)
        {
            innerResult.Add(A[i][j]);
        }
        else
        {
            innerResult.Add(innerResult[j - 1]);
        }
    }
    B.Add(innerResult);
}

这篇关于C#for二维列表循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆