2017-11-05 4 views
0

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

関数を呼び出す関数を追加する:

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); 
    } 
+0

最初の質問はありますか?このタイプの方がはるかに簡単です。 –

+0

私はそれがSQLの方が簡単だと知っていますが、私はC#だけを使ってタスクを実行しなければなりません。 – Kaloyan

+0

あなたのメソッドのより良い署名は 'public static List ReadFromFile(string filePath)'です。 – Enigmativity

答えて

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)を行うと、それは私がしました、今あなたに、各学生

+0

ありがとうございます。私は今日後でそれをテストし、私は何か質問があるかどうかを知らせます。 – Kaloyan

+0

ファイルからのデータをどこに正確に追加するのか分かりません。説明できますか? – Kaloyan

+0

ファイルの行の配列を使用する代わりに 'string [] yourFile'が表示されます –

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を自動的にインクリメントします。ここで

は(私は private static IEnumerable<Student> AskForStudents()方法に変更) AddStudent方法です:

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

// int型のid = -1; // do // { // Console.Write( "1.学生IDを入力:"); //} 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; 
     } 
    } 
} 

このようにあなたは今、それを使用します。あなたは、SQLを使用していない理由を

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

おい、それは完璧に働いた。しかし、そのidはちょっと変わっているようです。自動増分する方法を知っていますか?新しい生徒を追加するたびに、自動的に新しいIDを作成します。私はaddStudent()関数を変更する必要があると思う。ここに私のaddStudent()関数があります:https://www.dropbox.com/s/cpuwpforpk1l9h6/addStudent.txt?dl=0 – Kaloyan

+0

@Kaloyan - 私は私の答えを更新しました。 – Enigmativity

+0

ありがとうございます。私は明日それを試してみると、私は質問がある場合あなたに尋ねます。 – Kaloyan

関連する問題