Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法将文本插入列表<;字符串>;_C#_List - Fatal编程技术网

C# 无法将文本插入列表<;字符串>;

C# 无法将文本插入列表<;字符串>;,c#,list,C#,List,我想在列表的某个位置添加字符串。我尝试使用List.Insert()方法以及InsertRange()。两人都给了我错误 //Using InsertRange() Method string[] msg = { "Hi", "There", "Good", "Morning" }; List<string> Lines=new List<string>; Lines.InsertRa

我想在列表的某个位置添加字符串。我尝试使用List.Insert()方法以及InsertRange()。两人都给了我错误

     //Using InsertRange() Method
     string[] msg = { "Hi", "There",
                        "Good", "Morning" };
     List<string> Lines=new List<string>;
     Lines.InsertRange(4, msg);

     //Using Insert() Method
     string[] msg = { "Hi, Good Morning" };
     List<string> Lines=new List<string>;
     Lines.Insert(1, msg);
//使用InsertRange()方法
字符串[]msg={“嗨”,“那里”,
“早上好”、“早上好”};
列表行=新列表;
行。插入范围(4,msg);
//使用Insert()方法
字符串[]msg={“你好,早上好”};
列表行=新列表;
行。插入(1,msg);

请建议解决方案。

Insert
方法采用
单字符串
而不是
数组

Lines.Insert(1, msg[0]);
InsertRange
的第一个参数是要插入的索引。您正在
4th
索引上插入数组,而
列表行
没有
4th索引。

0索引上插入数组

Lines.InsertRange(0, msg);

首先,您必须修复代码中的语法错误,即必须声明如下字符串列表:
list Lines=new list()在您的情况下,您错过了
()
(希望不是打字错误)。然后对于Insert和InsertRange,给定的索引应该是有效的。这意味着指定的索引将在集合中可用

考虑第一个片段,
InsertRange

在此阶段集合为空,您正在尝试插入索引
4
,该索引在此阶段无效,并导致ArgumentOutOfRangeException。所以你可以试试看

 Lines.InsertRange(0, msg);
还可以尝试使用AddRange代替InserRange,这在这种情况下也很有用:

Lines.AddRange(msg);

现在让我考虑一下第二个片段。使用
.Insert
方法,您可以将项目插入到集合中的有效索引中。但在您的例子中,您试图将字符串数组插入到列表中的索引中,这是不允许的,您必须为数组指定单个字符串。请记住,索引是一个重要的因素,应该是有效的。如果不希望新元素处于特定位置,也可以尝试.Add()。它将被添加到最后一个位置。

这给了我一个错误,参数类型“string”不可分配给参数类型“System.COllections.Generic.IEnumerable”。是的,我已将list定义为msg=new list(10)@BhushanKhajone:您将字符串的大小限制为
10
,那么为什么不继续使用数组呢?无论如何,我已经更新了答案,你能看一下吗?有太多的基本错误(),我建议你买一本关于C#编程的书。