簡體   English   中英

我無法從FileText C#中讀取

[英]I can't Read from FileText C#

我必須像這樣在學生,班級和年份之間建立聯系:一年可以有1個或更多的班級,而1個班級可以有1個或更多的學生。

我用通用列表來做到這一點。 問題是我必須從一個.txt文件中獲取信息,但我不知道該怎么做。

我的文件是這樣的:

(Year,Class,Name,Surname,Average).
1   314 George      Andrew  8
2   324 Popescu     Andrei  9
2   323 Andreescu   Bogdan  10
3   332 Marin       Darius  9
3   332 Constantin  Roxana  10

碼:

  public class Student
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Average { get; set; }
    }
}


    public class Grupa
    { 
        public int Name { get; set; }
        public List<Student> SetStudent { get; set; }

        public Grupa()
        {
            SetStudent = new List<Student>();
        }

        public void Print()
        {
            //Console.WriteLine("Grupa: " + this.Name);
            Console.WriteLine("Studentii din grupa: ");

            foreach (Student s in this.SetStudent)
            {
                Console.WriteLine(" " + s.Name+ " " + s.Surname + "  ---  " + s.Average+"\n");
            }
        }
     }
public class An
    {
        public int Anul { get; set; }
        public List<Grupa> SetGrupa { get; set; }

        public An()
        {
            SetGrupa = new List<Grupa>();
        }

        public void Print()
        {
            Console.WriteLine("Anul: " + this.Anul);
            Console.WriteLine("Grupele din acest an: ");
            foreach (Grupa g in this.SetGrupa)
            {
                Console.WriteLine(" " + g.Name);
            }
        }
              }



    string[] lines = System.IO.File.ReadAllLines(@"D:\C#\Tema1\Tema1.txt");

    System.Console.WriteLine("Content Tema1.txt= \n");
    foreach (string line in lines)
    {
          Console.WriteLine("\t" + line);
    }

    Console.WriteLine("\n Close");
    System.Console.ReadKey();
}

您還可以將.NET TextFieldParser用於該類型的平面文件:

var studentList = new List<Student>();

var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser("<file path>");
parser.SetFieldWidths(4, 4, 12, 8, 2);

while (!parser.EndOfData)
{
     string[] line = parser.ReadFields();

     var student = new Student();
     student.Year = int.Parse(line[0]);
     student.Class = int.Parse(line[1]);
     student.Name = line[2].Trim();
     student.Surname = line[3].Trim();
     student.Average = int.Parse(line[4]);

     studentList.Add(student);
}

您只需要在SetFieldWidths函數中設置字段長度。

您的問題很模糊 ,您是否正在尋找這樣的Linq

// Parsing into objects
var data = System.IO.File
  .ReadLines(@"D:\C#\Tema1\Tema1.txt")
  .Skip(1) //TODO: comment down this line if your file doesn't have a caption
  .Select(line => line.Split('\t'))
  .Select(items => new { // or "new Student() {" if you've designed a Student class
    Year    = int.Parse(items[0]),
    Class   = int.Parse(items[1]),
    Name    = items[2],
    Surname = items[3],
    Average = int.Parse(items[4]), //TODO: Is it Int32 or Double?
  });

...

// combining back: 
String result = String.Join(Environment.NewLine, data
  .Select(item => String.Join("\t", 
     item.Year, item.Class, item.Name, item.Surname, item.Average));

Console.Write(result);

如果您想完全控制自己想做的事,建議您為每個學生創建一個類。

粗略的方法:

namespace ConsoleApplication1
{

    class Student
    {
        //Members of class
        public int Year;
        public int Class;
        public string FirstName;
        public string LastName;
        public int Average;

        /// <summary>
        /// Gets a line and creates a student object
        /// </summary>
        /// <param name="line">The line to be parsed</param>
        public Student(string line)
        {
            //being parsing

            //split by space
            List<String> unfiltered = new List<string>(line.Split(' '));

            //a list to save filtered data
            List<string> filtred = new List<string>();

            //filter out empty spaces...
            //There exist much smarter ways...but this does the job 
            foreach (string entry in unfiltered)
            {
                if (!String.IsNullOrWhiteSpace(entry))
                    filtred.Add(entry);
            }

            //Set variables
            Year = Convert.ToInt32(filtred[0]);
            Class = Convert.ToInt32(filtred[1]);
            FirstName = filtred[2];
            LastName = filtred[3];
            Average = Convert.ToInt32(filtred[4]);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var data = System.IO.File.ReadAllLines(@"d:\data.txt");

            //a list to hold students
            List<Student> students = new List<Student>();

            foreach (var line in data)
            {
                //create a new student and add it to list
                students.Add(new Student(line));
            }

            //to test, write all names
            foreach (var student in students)
            {
                Console.WriteLine(student.FirstName + " " + student.LastName + Environment.NewLine);
            }

            //you can calculate average of all students averages!
            int sum = 0;
            for (int i = 0; i < students.Count; i++)
            {
                sum += students[i].Average;
            }

            //print average of all students
            Console.WriteLine("Average mark of all students: " + (sum / students.Count));

            Console.ReadKey();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM