有没有办法拆分数组中的每个字符串并每次检索第 5 位,添加到总数中?

我对 C# 和一般编程还很陌生。


我有一个我正在阅读的文本文件,其中包含 10 行(除了第一行之外的所有行都是相关的)。


我想用逗号分隔每一行(除了第一行,因为它只有一个词),然后检索每行的第 5 行,将其添加到总数中。


目前我所能做的基本上是拆分并将相同的值添加到总数中 10 次,而不是将 9 个不同的值加在一起,否则将面临“System.IndexOutOfRangeException”。


            int totalValues = 0;


            string[] larray = lines.ToArray(); //create array from list

            string vehicleValue;


            for (int i = 0; i < larray.Length; i++)

            {

                string[] bits = larray[i].Split(','); 

                vehicleValue = bits[4];

                int vvint = int.Parse(vehicleValue);

                totalValues = totalValues + vvint; 

            }

            totalValue.Text = totalValues.ToString(); 

就目前而言,上述代码导致“System.IndexOutOfRangeException”突出显示“vehicleValue = bits [4];”


除了第一行之外,文件的每一行都像这样。


Car,Ford,GT40,1964,250000,987,Red,A1,2,4,FALSE

我希望从此特定行中得到的值是“250000”——第 5 个。我试图从每一行中获得第 5 个。


交互式爱情
浏览 71回答 2
2回答

喵喵时光机

您的问题是您还试图解析第一行(其中不包含足够的条目,因此您会得到异常)。您可以通过在索引 1 处开始迭代来跳过第一行:&nbsp; &nbsp; &nbsp; &nbsp; int totalValues = 0;&nbsp; &nbsp; &nbsp; &nbsp; string[] larray = lines.ToArray(); //create array from list&nbsp; &nbsp; &nbsp; &nbsp; string vehicleValue;&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 1; i < larray.Length; i++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string[] bits = larray[i].Split(',');&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; vehicleValue = bits[4];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int vvint = int.Parse(vehicleValue);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; totalValues = totalValues + vvint;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; totalValue.Text = totalValues.ToString();&nbsp;

天涯尽头无女友

bits[4]是数组中的第五项,因为索引从零开始,要获得第四项,您应该获得bits[3]int totalValues = 0;string[] larray = lines.ToArray(); //create array from liststring vehicleValue;for (int i = 0; i < larray.Length; i++){&nbsp; &nbsp; string[] bits = larray[i].Split(',');&nbsp;&nbsp; &nbsp; vehicleValue = bits[3];&nbsp; &nbsp; int vvint = int.Parse(bits[3]);&nbsp; &nbsp; totalValues = totalValues + vvint;&nbsp;}totalValue.Text = totalValues.ToString();&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP