索引数组错误

时间:2017-11-21 07:02:48

标签: c#

嗨,我遇到了一个问题,我一直收到这个错误:

  

索引超出了数组的范围。

var d = File.ReadAllLines(@"studentsFile.txt");
var t = d.Where(g => g.Contains("Student Name"));
string[] splited;
foreach (var item in t)
{
    splited = item.Split(new string[] { "Student Name:" }, StringSplitOptions.None);
    cbListStudents.Items.Add(splited[1]);
}

以上工作完美,但下面的代码不是:

var cour = File.ReadAllLines(@"CourseFile.txt");
var courFind = cour.Where(g => g.Contains("Course"));
string[] splited2;
foreach (var item in courFind)
{
    splited2 = item.Split(new string[] { "Course:" }, StringSplitOptions.None);
    cbListCourses.Items.Add(splited2[1]);//here is where the issues starts
}

4 个答案:

答案 0 :(得分:0)

至少你应该检查数组长度:

var cour = File.ReadAllLines(@"CourseFile.txt");
var courFind = cour.Where(g => g.Contains("Course"));
string[] splited2;
foreach (var item in courFind)
{
  splited2 = item.Split(new string[] { "Course:" }, StringSplitOptions.None);
  if(splited2.Length >= 2)
    cbListCourses.Items.Add(splited2[1]);//here is where the issues starts
}

答案 1 :(得分:0)

foreach (var item in courFind)
{
   splited2 = item.Split(new string[] { "Course:" }, StringSplitOptions.None);
   cbListCourses.Items.Add(splited2[0]); // Array Index starts with 0
}

答案 2 :(得分:0)

您必须检查数组的Length(如果该文件有,例如<​​em>空行,该怎么办?)

var data = File
  .ReadLines(@"CourseFile.txt")
  .Select(line => new string[] { "Course:" }, StringSplitOptions.None)
  .Where(items => item.Length >= 2) // Check array's Length
  .Select(items => items[1])        // Now it's safe to address the 2nd item  
  .ToArray();                       // ComboBox.Items.AddRange wants array

cbListCourses.Items.AddRange(data);

答案 3 :(得分:0)

该行文件中可能不包含任何冒号(:)。

你应该检查好像

var courFind = cour.Where(g => g.Contains("Course:"));

而不是之前的。

测试用例:

  1. 带有空内容
  2. 的文件
  3. 内容 - &gt;的课程:
  4. 内容 - &gt; 课程(与您面临的错误相同)
  5. 代码:

     var cbListStudents = new List<String> ();
     var cbListCourses = new List<String> ();
    
     var d = File.ReadAllLines (@"res/TestFile.txt");
     var t = d.Where (g => g.Contains ("Student Name"));
     string[] splited;
     foreach (var item in t) {
        splited = item.Split (new string[] { "Student Name:" }, StringSplitOptions.None);
        cbListStudents.Add (splited[1]);
     }
    
     var cour = File.ReadAllLines (@"res/TestFile2.txt");
     var courFind = cour.Where (g => g.Contains ("Course"));
     string[] splited2;
     foreach (var item in courFind) {
        splited2 = item.Split (new string[] { "Course:" }, StringSplitOptions.None);
        cbListCourses.Add (splited2[1]); //here is where the issues starts
     }