将学生数据从文件加载到列表中

时间:2017-11-05 12:11:28

标签: c# list file

我对c#很新。但是,我想从.txt文件加载数据,然后自动将该数据填入我的列表。我该怎么办?

我希望ReadFromFile函数能够使用文件中的数据自动填充列表。因为在我调用SortData函数之后,我想使用文件中的数据,而不是手动再次添加所有数据。

我设法从文件加载数据,但在此之后无法填写列表。

这是我的.txt文件

 Name: Bob   Position: CEO   Intern: 7   Salary: 7000
 Name: Toti  Position: Freelancer    Intern: 4   Salary: 4000
 Name: Mike  Position: www   Intern: 5   Salary: 5000
 Name: Vanko     Position: Badass    Intern: 5   Salary: 5000

这是我的ReadFromFile函数:

    //READ FROM FILE
    public static void ReadFromFile(List<Student> existingStudents, string 
filePath)
    {
        StreamReader reader = new StreamReader(filePath);

        while (!reader.EndOfStream)
        {
            Console.WriteLine(reader.ReadLine());
        }
        reader.Close();

        foreach (Student stud in existingStudents)
        {
            existingStudents.Add(new Student(stud.id, stud.Name, stud.Position, stud.Internship));
            Console.WriteLine(stud.ToString());
        }
    }

我也有班级学生,他有以下属性:

class Student
    {
    public int id;
    public string name;
    public double salary;
    public string position;
    public int intern;

    public Student(int id, string name, string position, int intern)
    {
        this.id = id;
        this.name = name;
        this.position = position;
        this.intern = intern;
    }
 }

在main函数中,我调用添加函数:

    static void Main(string[] args)
    {

        List<Student> st = new List<Student>();

        String filePath = "test.txt";
        switch (answer)
              {
                case 1:
                    WriteToFile(st, filePath);
                    Console.WriteLine("File Created!");
                    break;
                case 2:
                    ReadFromFile(st, filePath);
                    break;
                case 3:
                    AddStudent(st);
                    break;
   } while (answer != 4);
  }

2 个答案:

答案 0 :(得分:0)

以下是我为您所处的情况编写的代码,但它需要对文本文件格式进行一些优化。

public class Student
{
    public string Name;
    public string Position;
    public string Intern;
    public string Salary;
}
public class Program
{
    public static void Main(string[] args)
    {
        string[] yourFile = System.IO.File.ReadAllLines(@"C:PathToFile\File.txt");

        List<Student> students = new List<Student>();

        foreach(string s in yourFile)
        {
            Student student = new Student();

            string[] dividedLines = s.Split('|');
            foreach(string line in dividedLines)
            {                    
                string[] data = line.Split(':');
                switch(data[0])
                {
                    case "Name":
                    student.Name = data[1];
                    break;
                    case "Position":
                    student.Position = data[1];
                    break;
                    case "Intern":
                    student.Intern= data[1];
                    break;
                    case "Salary":
                    student.Salary = data[1];
                    break;
                }
            }
            students.Add(student);
        }
    }
}

如果您的文本文件中的行如下所示,则可能更容易:

Bob|Ceo|7|7000

因为我们只需要使用一次拆分。

这样你就可以将数据存储在List中,如果你想显示一些学生数据,你可以在名单中轻松找到它,或者只是foreach(Student s in students),它会给你每个学生

答案 1 :(得分:0)

现在,我已将您的Student类修改为更加惯用,并接受源文件中的字段到构造函数。它现在看起来像:

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Salary { get; set; }
    public string Position { get; set; }
    public int Intern { get; set; }

    public Student(string name, string position, int intern, decimal salary)
    {
        this.Name = name;
        this.Position = position;
        this.Intern = intern;
        this.Salary = salary;
    }
}

然后,鉴于我可以将您的ReadFromFile方法签名更改为惯用,我创建了这个:

public static List<Student> ReadFromFile(string filePath)
{
    var students =
        from line in File.ReadAllLines(filePath)
        let parts =
            line
                .Trim()
                .Split('\t')
                .Select(x => x.Trim().Split(':').Select(y => y.Trim()).ToArray())
                .ToDictionary(y => y[0], y => y[1])
        select new Student(parts["Name"], parts["Position"], int.Parse(parts["Intern"]), decimal.Parse(parts["Salary"]));

    return students.ToList();
}

现在您的代码如下所示:

List<Student> students = ReadFromFile(filePath);

根据您的评论,这是我修改代码的方式:

public class Student
{
    private int _next_id = 0;
    public int Id { get; private set; }
    public string Name { get; set; }
    public decimal Salary { get; set; }
    public string Position { get; set; }
    public int Intern { get; set; }

    public Student(string name, string position, int intern, decimal salary)
    {
        this.Id = _next_id++;
        this.Name = name;
        this.Position = position;
        this.Intern = intern;
        this.Salary = salary;
    }
}

自动递增学生ID。

这是AddStudent方法(我更改为private static IEnumerable<Student> AskForStudents()方法):

private static IEnumerable<Student> AskForStudents()
{
    while (true)
    {
        Console.WriteLine("Enter new student information");

// int id = -1; //做 // { // Console.Write(&#34; 1.输入学生ID:&#34;); //} while(!int.TryParse(Console.ReadLine(),out id));

        Console.Write(" 2. Enter student Name: ");
        string name = Console.ReadLine();

        Console.Write(" 3. Enter student Job Title: ");
        string jobTitle = Console.ReadLine();

        int yrsOfService = -1;
        do
        {
            Console.Write(" 4. Enter student years of service: ");
        } while (!int.TryParse(Console.ReadLine(), out yrsOfService));

        decimal salary = -1m;
        do
        {
            Console.Write(" 4. Enter salary: ");
        } while (!decimal.TryParse(Console.ReadLine(), out salary));

        yield return new Student(name, jobTitle, yrsOfService, salary);

        Console.WriteLine("Do you want to add another Student? y/n");
        if (Console.ReadLine() == "n")
        {
            yield break;
        }
    }
}

您现在可以像这样使用它:

var students = ReadFromFile(filePath);
students.AddRange(AskForStudents());