使用c#进行迭代的最佳方式是什么?

使用c#进行迭代的最佳方式是什么?,c#,C#,我有一个包含数据的文件。 以下是链接: 任务是迭代并添加第三列的值(从1-0-0..3..11..开始)。34是总数 最好的方法是什么?我是c#的初学者,因此任何帮助都将不胜感激。谢谢 static void Main(string[] args) { string line; int sum = 0; // Read the file and display it line by line.

我有一个包含数据的文件。 以下是链接:

任务是迭代并添加第三列的值(从1-0-0..3..11..开始)。34是总数

最好的方法是什么?我是c#的初学者,因此任何帮助都将不胜感激。谢谢

    static void Main(string[] args)
    {
                   string line;
        int sum = 0;
        // Read the file and display it line by line.
        System.IO.StreamReader file =
           new System.IO.StreamReader(@"C:\temp\test.txt");
        while ((line = file.ReadLine()) != null)
        {
            char[] delimiters = new char[] { '|' };
            string[] arr = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
            if (string.IsNullOrEmpty(line)) break;
            Console.WriteLine(arr[2]);

            sum += Int32.Parse(arr[2]);

        }
        Console.WriteLine(sum);
        Console.ReadLine();
        file.Close();
    }
我得到一个System.IndexAutoFrangeException


{“索引超出了数组的边界。”}我做错了什么?

StackOverflow不是设计、编码或教程服务。发布带有特定问题的适用代码,您就更有可能获得所需的帮助。一些有用的函数包括
File.ReadAllLines(string)
string.Split(char[])
,以及
foreach
是,抱歉。我添加了代码和异常。这是因为您的最后一行没有足够的列。拆分时出错。我改为line.Split(新字符串[]{“|”},StringSplitOptions.None);但这不起作用。试着把线铸成线。所以(string)line.split(“|”)作为起点,在internet上寻找其他资源,帮助您理解如何在C#中拆分字符串。期望堆栈溢出只为您完成所有工作是不礼貌的。
string line;
int sum = 0;
// Read the file and display it line by line.
System.IO.StreamReader file = 
   new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
   string[] arr = line.split("|"); // split the line into an array
   sum += Int32.Parse(arr[2]); // get the 3rd element in the row an convert it to int
}

file.Close();