假设我有一个数组
string[] A = {"1","2","3","4","5"}
Run Code Online (Sandbox Code Playgroud)
我希望数组的大小为10,并想在某个索引之后插入空白字符串。
例如,我可以将其设置为10,并在索引3之后插入字符串,这将导致
A = {"1","2","3","4","","","","","","5"}
Run Code Online (Sandbox Code Playgroud)
基本上,给定索引之后的元素将被推到末尾,空白字符串将占据它们之间的空白。
这是我尝试过的方法,但是它只添加了一个字符串,并没有为数组精确设置大小
var foos = new List<string>(A);
foos.Insert(33, "");
foos[32] = "";
A = foos.ToArray();
Run Code Online (Sandbox Code Playgroud)
You can use InsertRange
var l = new List<string>{"1","2","3","4","5"};
l.InsertRange(3, new string[10 - l.Count]);
foreach(var i in l)
Console.WriteLine(i);
Run Code Online (Sandbox Code Playgroud)
Note: The above doesn't populate with empty strings but null values, but you can easily modify the new string[] being used to be populated with your desired default.
For example; see How to populate/instantiate a C# array with a single value?
| 归档时间: |
|
| 查看次数: |
1562 次 |
| 最近记录: |