如何插入嵌套列表

时间:2018-06-30 13:22:15

标签: c# .net

我初始化列表列表:

List<List<double>> List = new List<List<double>>();
for(int k = 0; k < 4; k++)
{
    liste_moyenne.Add(new List<double>(5));
}

我想插入一个列表的值(此列表由另一个函数生成),如下所示:

Insertion in a nested list

为此,我做了这段代码:

for (int i = 0; i < List.Count; i++)
{
    for (int j = 0; j < myList.Count; j++)
    {
        List[i].Add(AddSmthToWork(myList[j]))
    }
}

我该怎么做?

2 个答案:

答案 0 :(得分:0)

下面是使用<div class="col-sm-12 col-lg-4 order-1 order-sm-2"> <!-- some contents here --> </div> <div class="col-sm-12 col-lg-8 order-2 order-sm-1"> <!-- some contents here --> </div> 方法的示例:

AddRange

输出:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var listOfList = new List<List<double>>();

        for (var i = 0; i < 4; i++)
        {
            listOfList.Add(new List<double>(5));
        }

        foreach (var item in listOfList)
        {
            item.AddRange(GetList(5));
        }

        for(var i = 0; i < listOfList.Count; i++)
        {
            for (var j = 0; j < listOfList[i].Count; j++)
            {
                Console.WriteLine($"listOfList[{i}][{j}] = {listOfList[i][j]}");
            }
        }
    }

    private static IList<double> GetList(int maxCapacity)
    {
        var newList = new List<double>(maxCapacity);

        for (var i = 0; i < maxCapacity; i++)
        {
            newList.Add(i);
        }

        return newList;
    }
}

答案 1 :(得分:0)

请参见this tutorial

List<List<double>> nestedList = new List<List<double>>();
for (int i = 0; i < 4/*myCount*/; i++)
{
    List<double> sublist = new List<double>();
    for (int j = 0; j < 4/*myCount*/; j++)
    {
        sublist.Add(/*myValue*/)
    }
    nestedList.Add(sublist);
}