1

我有一个名为 lst 的 List<string[]>:

[0] "ABC" "DEF" "GHI"
[1] "JKL" "MNO" "PQR"
[2] etc, etc...

如何在每个 lst 成员的末尾添加另一个字符串?

字符串 s = "EndOfBlock";

[0] "ABC" "DEF" "GHI" "EndOfBlock"
[1] "JKL" "MNO" "PQR" "EndOfBlock"
[2] etc, etc...

谢谢你。

4

5 回答 5

5

应该是这样的:

var lst = new List<string[]>();
lst.Add(new string[] { "ABC", "DEF" });
lst.Add(new string[] { "GHI", "JKL" });

foreach (var item in lst)
{
    Console.WriteLine(item.Length);
}

for (int i = 0; i < lst.Count; ++i)
{
    var array = lst[i];
    Array.Resize(ref array, array.Length + 1);
    array[array.Length - 1] = "EndOfBlock";
    lst[i] = array;
}

foreach (var item in lst)
{
    Console.WriteLine(item.Length);
}

Array.Resize参考

于 2012-09-25T16:35:51.077 回答
3

正如评论者所指出的,听起来你真的想要一个List<List<string>>. 但是,如果您想坚持使用List<string[]>,这就是我扩展每个数组的方式。

List<string[]> list = ...
for(int i = 0; i < list.Count; i++)
{
    // copy to a local variable (list[i] is a property, which can't be passed 'ref')
    string[] array = list[i];

    // resize the local variable. (this creates a new string[] object)
    Array.Resize(ref array, array.Length + 1);
    array[array.Length - 1] = "EndOfBlock";

    // put the new object back in the list, replacing the old smaller one.
    list[i] = array;
}
于 2012-09-25T16:42:10.257 回答
1

我还建议您使用List<List<string>>

List<List<string>> lst = new List<List<string>>();
lst.ForEach(i=>i.Add("EndOfBlock"));     
于 2012-09-25T16:39:42.807 回答
0

如果要保留数组列表,可以这样做:

List<string[]> lst = new List<string[]); //Where this is the poplated list instead of new;
for (ini i = 0; i < lst.Count; i++)
{
   List<string> tmpList = new List<string>(lst[i]);
   tmpList.Add("EndOfBlock");
   lst[i] = tmpList.ToArray();
}
于 2012-09-25T16:46:25.777 回答
0

如果你真的想这样做,IList<string[]>你可以这样做,

var lst = new List<string[]>
{
    { "ABC", "DEF", "GHI" },
    { "JKL", "MNO", "PQR" },
    ...
}

var blockEnd = new string[] { "EndOfBlock" };

lst = lst.Select(a => 
    (a.Select(s => s).Concat(blockEnd))
    .ToArray()).ToList();

如果lstIlist<Ilist<string>>.

var lst = new List<List<string>>
{
    { "ABC", "DEF", "GHI" },
    { "JKL", "MNO", "PQR" },
    ...
}

foreach(var row in lst)
{
   row.Add("EndOfBlock");
}
于 2012-09-25T16:44:45.920 回答