C#如何将List<string>添加到List<List<string>>数组中

9

我可以通过以下方式将List<string>添加到List<List<string>>数组中:

        List<string> first = new List<string> { "one", "two", "three" };
        List<string> second = new List<string> { "four", "five", "six" };

        List<List<string>> list_array = new List<List<string>> { first, second };

现在我需要创建几个填充有数据库记录的列表,并将这些列表添加到 List<List<string>> 数组中:

    List<List<string>> array_list;

            while (dr.Read())
            {
                string one = dr["Row1"].ToString();
                string two = dr["Row2"].ToString();

                List<string> temp_list = new List<string> { one, two };

                //Here I need to add temp_list to array_list
            }

2
你在这里有什么问题?你不能将temp添加到数组中吗?你尝试过什么?你是否收到任何错误信息? - Ravi Y
2
@ryadavilli 他在询问如何将temp_list添加到array_list中,他展示了自己已经尝试创建这些列表,但不确定如何继续操作,因为他还没有添加它。他之前的尝试添加的代码没有显示出来,因为它们要么导致编译错误,要么无法正常工作,而他已经发现了这一点。还有其他问题吗? :P - user1645826
@RhysW 很高兴你理解了他的意图。但并不是每个人都能痛苦地明显看出来。因此,我问了这些问题。在SO上,我们期望有问题,而不是因为示例中没有代码而推断出缺少某些东西。此外,我们期望发布者提到他们尝试过什么以及他们卡在哪里。 - Ravi Y
@ryadavilli,你可以在注释行中看到我的问题://这里我需要将temp_list添加到array_list中。 同时,我解释了我要做什么:现在我需要创建几个填充有数据库记录的列表,然后将这些列表添加到List<List<string>>数组中。 - Mega
8个回答

10
创建一个空的array_list:
List<List<string>> array_list = new List<List<string>>();

然后使用Add方法添加项目:

array_list.Add(temp_list);

3
将变量声明更改为初始化一个空列表:
将变量声明更改为初始化一个空列表。
List<List<string>> array_list = new List<List<string>>();

然后,只需要调用 .Add() 方法。
List<string> temp_list = new List<string> { one, two };

//Here I need to add temp_list to array_list
array_list.Add(temp_list);

2
这应该可以运行:
array_list.Add(temp_list);

2
List<List<string>> array_list = new List<List<string>>();

while (dr.Read())
{
   string one = dr["Row1"].ToString();
   string two = dr["Row2"].ToString();
   List<string> temp_list = new List<string> { one, two };
   array_list.add(temp_list)
}

2
List<List<string>> array_list = new List<List<string>>();
while (dr.Read())
        {
            string one = dr["Row1"].ToString();
            string two = dr["Row2"].ToString();

            List<string> temp_list = new List<string> { one, two };

            array_list.Add(temp_list);
        }

2
除非我理解有误,您应该只需要执行以下操作即可:

array_list.add(temp_list);

2
只有在他的第一个array_list实例化设置为新的List<List<String>>时,才能开始。 - user1645826

1

您可以直接添加;

array_list.Add(temp_list);

0

在编程中,你必须时刻记得创建新的 temp_list,不要像我在项目中一样使用 temp_list.clear() =_=。

引用

 List<List<string>> array_list = new List<List<string>>();
    while (dr.Read())
            {
                string one = dr["Row1"].ToString();
                string two = dr["Row2"].ToString();

                List<string> temp_list = new List<string> { one, two };

                array_list.Add(temp_list);
            }

引用


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