C#如何将字符串列表添加到列表

时间:2018-08-01 12:52:38

标签: c#

我正在尝试将<action name="MyAction_*" class="MyActionClass" method="{1}"> 添加到list of string。以下是我的代码

list

但是当我using System; using System.Collections.Generic; public class Program { public static void Main() { List<string> customBindingRow = new List<string>(); List<List<string>> customBindingData = new List<List<string>>(); for (int i = 0; i < 10; i++) { customBindingRow.Clear(); for (int j = 0; j < 2; j++) { customBindingRow.Add("i=" + i.ToString() + "j=" + j.ToString()); } customBindingData.Add(customBindingRow); } string text = ""; foreach (List<string> dt in customBindingData) { text += string.Join(",", dt.ToArray()) + "\r\n"; } Console.WriteLine(text); } } 时,它仅显示最后添加的Console.WriteLine

这是输出

list

预期产量

i=9j=0,i=9j=1
i=9j=0,i=9j=1
i=9j=0,i=9j=1
i=9j=0,i=9j=1
i=9j=0,i=9j=1
i=9j=0,i=9j=1
i=9j=0,i=9j=1
i=9j=0,i=9j=1
i=9j=0,i=9j=1
i=9j=0,i=9j=1  

4 个答案:

答案 0 :(得分:2)

实际上,customBindingRow是用于循环10次的同一对象。您只需清除每个循环的内容即可。

您必须重新初始化customBindingRow,而不是Clear

var customBindingData = new List<List<string>>();
for (int i = 0; i < 10; i++)
{
    var customBindingRow = new List<string>();
    for (int j = 0; j < 2; j++)
    {
        customBindingRow.Add("i=" + i.ToString() + "j=" + j.ToString());
    }

    customBindingData.Add(customBindingRow);
}

答案 1 :(得分:1)

您添加在

中创建的相同对象
List<string> customBindingRow = new List<string>();

通过清除并添加新字符串,对对象进行10次和10次修改。

只需用创建要插入集合的新对象来代替清除。

customBindingRow.Clear();

=>

customBindingRow = new List<string>();

答案 2 :(得分:1)

您几乎接近预期的答案。不要初始化customBindingRow,只需创建它并用customBindingRow.Clear()替换customBindingRow = new List<string>;行,因为.Clear()将从列表中删除所有项目。

 List<string> customBindingRow;
 List<List<string>> customBindingData = new List<List<string>>();

 for (int i = 0; i < 10; i++)
 {
      customBindingRow = new List<string>();
      for (int j = 0; j < 2; j++)
      {
           customBindingRow.Add("i=" + i.ToString() + "j=" + j.ToString());
      }

      customBindingData.Add(customBindingRow);
  }
  string text = "";
  foreach (List<string> dt in customBindingData)
  {
      text += string.Join(",", dt.ToArray()) + "\r\n";
  }

  Console.WriteLine(text);

希望这对您有所帮助。

答案 3 :(得分:0)

在您的示例中,您修改了customBindingRow,最后customBindingData拥有相同列表的十倍。

最后,对字符串进行分配不是有效的方法。请改用StringBuilder类。

相反,您可以这样尝试:

List<string> customBindingRow;
List<List<string>> customBindingData = new List<List<string>>();
for (int i = 0; i < 10; i++)
{

    customBindingRow = new List<string>();
    for (int j = 0; j < 2; j++)
    {
        customBindingRow.Add("i=" + i.ToString() + "j=" + j.ToString());
    }

    customBindingData.Add(customBindingRow);
}

//Using stringbuilser will reduce the memory usage.
//Adding text to a string will create a new reference in memory, you should avoid this.
StringBuilder text = new StringBuilder();

foreach (List<string> dt in customBindingData)
{
    text.Append( string.Join(",", dt.ToArray()) + "\r\n");
}

Console.WriteLine(text.ToString());