简体   繁体   中英

Importing CSV File in C# Convert the string list to specific classtype list

First i have to mention that iam not that good in programming but i try my best. Following situation: I imported several csv files into string lists. Now i want to cast those lists as the classdatatype i need. For example class Student, in the studentlistmanager class iam improting the list and trying to convert it to List but it seems like it wont be that easy, i tried to create an object of that list and add the object to the student list but that wont work either. Instead of the values i get System.String[] values into my list.

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();

              }
            }
        }

I would really appreciate any help. Thanks in advance!

Is that what you are looking for ? Saving the Data of the csv File in the Student List.

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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM