IndexOutOfRangeException未处理

时间:2016-09-13 07:31:37

标签: c# indexoutofrangeexception unhandled

我在第requires: ["MY_APP.view.Main"]行收到错误IndexOutOfRangeException was unhandled

我的.csv文件显示:

int euros = int.Parse(values[1])
name,   1,  2
name1,  3,  4
name2,  5,  6

2 个答案:

答案 0 :(得分:0)

在您按分号分割的代码中,您的CSV输入是逗号。将EntitySearcher参数更改为split()

,

您可能还想添加输入格式检查以确保string[] values = line.Split(','); 数组包含至少三个项,并且数字字段实际上包含整数值(values可能对此有帮助):

int.TryParse()

答案 1 :(得分:0)

您可能在CSV文件中有一些空行。 我建议使用 Linq 来总结欧元:

var data = File
  .ReadLines("C:\\Users\\Andrius\\Desktop\\Mokslams\\C#\\Pratybos\\P2\\P2.1\\turistai.csv")
  .Select(line => line.Split(','))
  .Where(items => items.Length >= 2) // filter out empty/incomplete lines
  // To debug, let's take euros only
  .Select(items => int.Parse(items[1]));
  // In the final solution we'll create Touristai instances
  // .Select(items => new Touristai(items[0], int.Parse(items[1]), int.Parse(items[2])))
  .ToArray();

Console.WriteLine(String.Join(Environment.NewLine, data));

Console.WriteLine(data.Sum());

最终解决方案将是

public static void ReadData(out Turistai[] tourists, out int amount) {
  tourists = File
    .ReadLines(@"C:\Users\Andrius\Desktop\Mokslams\C#\Pratybos\P2\P2.1\turistai.csv")
    .Select(line => line.Split(','))
    .Where(items => items.Length >= 2) // filter out empty/incomplete lines
    .Select(items => new Touristai(items[0], int.Parse(items[1]), int.Parse(items[2])))
    .ToArray();

  //TODO: check syntax (I've sugested Touristai should have Euro property) 
  amount = tourists.Sum(tourist => tourist.Euro); 
}