在String数组中插入一个元素

usr*_*986 7 c# arrays

我有包含n个元素的字符串.

我想在第一个位置插入一个自动递增的数字.

例如数据

66,45,34,23,39,83
64,46,332,73,39,33 
54,76,32,23,96,42
Run Code Online (Sandbox Code Playgroud)

我正在拆分字符串到数组与拆分字符','

我想要一个增加数字的结果数组作为第一个位置

1,66,45,34,23,39,83
2,64,46,332,73,39,33
3,54,76,32,23,96,42
Run Code Online (Sandbox Code Playgroud)

请建议我该怎么做.

谢谢

Kie*_*one 17

您不能使用数组,而是需要使用数组List<string>.

例如:

List<string> words = new string[] { "Hello", "world" }.ToList();
words.Insert(0, "Well");
Run Code Online (Sandbox Code Playgroud)

  • 使用它会不会更清晰:List <string> words = new List <string> {"Hello","World"}; ? (8认同)

MAX*_*AXE 11

Linq有一个简单的方法来完成你的"使命":

首先添加正确的命名空间:

using System.Linq;
Run Code Online (Sandbox Code Playgroud)

然后:

// Translate your splitted string (array) in a list:
var myList = myString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList<string>();

// Where insertPosition is the position you want to insert in:
myList.Insert(insertingPosition, insertedString);

// Back to array:
string[] myArray = myList.ToArray<string>();
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助...


Ole*_*nyk 5

您不能向 Array 插入任何内容。使用List<T>来代替。