如何忽略CSV文件的前两列

时间:2018-12-10 00:33:36

标签: c#

我正在尝试读取一个.csv文件,该文件包含学生的姓名,学生的ID和许多年级的列,并使用该信息在类似于John的列表框中写行-> 12345-> 89.50 ,其中第一个值是学生姓名,第二个值是学生ID,第三个值是测验分数的平均值。

我能够读取文件并将令牌[0]分配给名称,将令牌1分配给ID,但我不知道如何从字符串获取剩余值(等级)。加倍,这样我就可以算算平均值。

enter image description here

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace McKensey
{
    //struct for students name, ID, grades
    struct Student
    {
        public string name;
        public string ID;
        public string grade;
    }

    public partial class Form1 : Form
    {
        //feild to hold a list of GradeEntry
        private List<Student> gradeList = new List<Student>();

        public Form1()
        {
            InitializeComponent();
        }

        //the ReadFile method reads thecontents of the .csv test and stores
        //it as Student objects in gradeList
        private void ReadFile()
        {
            StreamReader inputFile;     //to read the file
            string line;                //to hold a line from the file
            double grade;
            double total = 0;

            //creat a instance of the Student structure
            Student entry = new Student();

            //create a delimiter array
            char[] delim = { ',' };

            //open the .csv file
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                //open the selected file
                inputFile = File.OpenText(openFile.FileName);

                //read the files data
                while (!inputFile.EndOfStream)
                {
                    //read the lines from the file
                    while (!inputFile.EndOfStream)
                    {
                        line = inputFile.ReadLine();

                        //tokenize the line
                        string[] tokens = line.Split(delim);

                        entry.name = tokens[0];
                        entry.ID = tokens[1];



                        gradeList.Add(entry);

                    }


                }
                //close file
                inputFile.Close();
            }
            else
            {
                MessageBox.Show("Opertaion Canceled.");
            }
        }
        private void DisplayInfo()
        {
            foreach (Student entry in gradeList)
            {

                listBox1.Items.Add(entry.name + "-->" + entry.ID + "-->" + entry.grade);
            }
        }


        private void processButton_Click(object sender, EventArgs e)
        {
            ReadFile();
            DisplayInfo();
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您可以简单地执行以下操作:

IEnumerable<string> strCSV =
            File.ReadLines(@"C:\\Users\\xxx\\Desktop\\Book1.csv");

var results = from str in strCSV
            let tmp = str.Split(',')
                .Skip(2)  // skip the first two columns
                .Select(q => Convert.ToInt32(q))
            select new
            {
                Max = tmp.Max(),
                Min = tmp.Min(),
                Total = tmp.Sum(),
                Avg = tmp.Average()
            };

        var query = results.ToList();

        foreach (var q in query)
        {
            Console.WriteLine(
                string.Format("Maximum: {0}, " +
                              "Minimum: {1}, " +
                              "Total: {2}, " +
                              "Average: {3}",
                    q.Max, q.Min, q.Total, q.Avg));
        }

答案 1 :(得分:0)

如果第三列是您的成绩列,则需要这样

 entry.name = tokens[0];
 entry.ID = tokens[1];
 entry.grade = Convert.ToDouble(tokens[2]);

编辑:我将字符串固定为双转换

当我们跟踪您的读取文件的代码段

  • 阅读line = inputFile.ReadLine();的行
  • 将线分割成碎片
    • 在这里,您要使用定界符将行字符串转换为字符串数组,
    • 数组从位置0开始直到长度-1(您的csv文件有7个列,因此您的数组从0开始,以6结尾)
  • 然后使用令牌[column_number]读取每一行

注意

您的代码有两个while条件while (!inputFile.EndOfStream),这没有意义。条件仅足以读取单个文件时,仅1。删除外部while条件。

编辑

您需要将Student.grade属性更改为double并使用entry.grade = Convert.ToDouble(tokens[2]);或将其保留为字符串并使用entry.grade = tokens[2]

struct Student
{
    public string name;
    public string ID;
    public double grade; //this line has modification 
}

答案 2 :(得分:0)

如果要将其余部分从Double转换为String,则可以执行以下操作:

 entry.grade = double.Parse(tokens[2]).ToString() + ',' + double.Parse(tokens[3]).ToString() + ',' + double.Parse(tokens[4]).ToString() + ',' + double.Parse(tokens[5]).ToString() + ',' + double.Parse(tokens[6]).ToString();

如果要处理错误,可以用try catch包裹它。