在C#中导入CSV文件将字符串列表转换为特定的classtype列表

问题描述 投票:0回答:1

首先,我不得不提一下,iam在编程方面不是那么好,但我会尽我所能。以下情况:我将几个csv文件导入到字符串列表中。现在我想将这些列表转换为我需要的classdatatype。例如,类student,在studentlistmanager类中,iam强制列表并尝试将其转换为List但似乎它不会那么容易,我试图创建该列表的对象并将该对象添加到学生列表但不会工作要么。而不是值我得到System.String []值到我的列表中。

internal void ImportStudentList(CsvImportService csv)
        {
            List<string> newList = new List<string>();
           csv = new CsvImportService("Klassenlisten_20160906.csv");
           for(int i = 0; i <= csv.ClassList.Count;i++)
            {
                for(int x = 0; x <= csv.ClassList.Count;x++)
              {
                    string line = csv.ClassList[i];
                    //  Student st = new Student(line);
                    //  ListOfStudents.Add(st);
                    newList.Add(line);
                    ListOfStudents = newList.Cast<Student>().ToList();

              }
            }
        }

我真的很感激任何帮助。提前致谢!

c# casting
1个回答
0
投票

那是你在找什么?将csv文件的数据保存在学生列表中。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;


namespace Stackoverflow_Konsole_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string CSV_FILE_PATH = @"filepath.csv";

            List<string> FULL_CSV_STRING = new List<string>();
            Students Student1 = new Students();

            FULL_CSV_STRING.Add(File.ReadAllText(CSV_FILE_PATH));

            foreach (string line in FULL_CSV_STRING)
            {
                Student1.add(line);               
            }

            foreach (string line in Student1.getlist())
            {
                Console.WriteLine(line);
            }
            Console.ReadLine();
        }
    }
}




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stackoverflow_Konsole_Test
{
    class Students
    {
        private List<string> List_of_students = new List<string>();


        public Students()
        {
            //constructor
        }

        public void add(string line)
        {
            this.List_of_students.Add(line);
        }         
        public List<string> getlist()
        {
            return this.List_of_students;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.