參考答案:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;//使用StreamReader必備
namespace CSD04
{
class Program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader(@"scores.txt");//指定要讀取的檔案
List<Student> students = new List<Student>();//事先宣告要存放Student資料用的List,裡面可放Student Class
while (!sr.EndOfStream)//『如果不是沒有資料』的話,就一直讀
{
string word = sr.ReadLine();//直接抓一行(Line)
string[] data = word.Split('\t');//以『Tab』作為分割資料的依據
students.Add(new Student(data[0], data[1], data[2], data[3]));//以抓到的資料創建Student Class
}
double avg_chi = students.Average(s => s.chi);//傳入List中的每一個Student,並取出chi的值做Avg計算
double avg_eng = students.Average(s => s.eng);
double avg_math = students.Average(s => s.math);
Console.WriteLine("AVG in Chinese: {0:.00}",avg_chi);
Console.WriteLine("AVG in English: {0:.00}",avg_eng);
Console.WriteLine("AVG in Math: {0:.00}",avg_math);
Console.Read();
}
}
class Student
{
public string id;
public int chi, eng, math;
public Student(string Id,string Chi,string Eng,string Math)
{
id = Id;
chi = int.Parse(Chi);
eng = int.Parse(Eng);
math = int.Parse(Math);
}
}
}
執行結果:
留言列表