我有一個.csv文件包含名稱,滾動,主題相應我解析成一個數據表,並計算每個主題的最高標記。我想要計算的是每個主題的平均值。誰能幫我這個 !!!!!如何找到一個數據表的每列的平均值使用c#
這是我的輸出。
爲ComputerScience最高分:
Name : Manoj
Roll Number : 1212334556
Mark : 94
生物學最高分:
Name : Sandeep
Roll Number : 1223456477
Mark : 90
工商最高分:
Name : BarathRam
Roll Number : 1212345664
Mark : 97
和CSV文件包含名稱,Rollno,計算機,生物學,商業。
現在我需要得到的是每個主題
的平均我的代碼:
static DataTable table;
static void Main(string[] args)
{
StreamReader r = new StreamReader(@"C:\Users\GOPINATH\Desktop\stud1.csv");
string line = r.ReadLine(); //reads first line - column header
string[] part = line.Split(','); //splits the line by comma
createDataTable(part);
//copy from CSV to DataTable<String,String,int,int,int>
while ((line = r.ReadLine()) != null)
{
try
{
part = line.Split(',');
table.Rows.Add(part[0], part[1], Convert.ToInt32(part[2]), Convert.ToInt32(part[3]), Convert.ToInt32(part[4]));
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
r.Close();
int mark1_index = 0, mark2_index = 0, mark3_index = 0; //initailize index value 0 for highest marks
//finding the index of the highest mark for each subject
for(int i=0 ; i<table.Rows.Count ; i++)
{
if (Convert.ToInt32(table.Rows[i][2]) > Convert.ToInt32(table.Rows[mark1_index][2])) //subject1
{
mark1_index = i;
}
if (Convert.ToInt32(table.Rows[i][3]) > Convert.ToInt32(table.Rows[mark2_index][3])) //subject2
{
mark2_index = i;
}
if (Convert.ToInt32(table.Rows[i][4]) > Convert.ToInt32(table.Rows[mark3_index][4])) //subject3
{
mark3_index = i;
}
}
printmark(table,mark1_index, 2);
printmark(table,mark2_index, 3);
printmark(table,mark3_index, 4);
Console.Read();
}
public static void createDataTable(string[] columnName)
{
//create DataTable<String,String,int,int,int>
table = new DataTable();
table.Columns.Add(columnName[0], typeof(String));
table.Columns.Add(columnName[1], typeof(String));
table.Columns.Add(columnName[2], typeof(int));
table.Columns.Add(columnName[3], typeof(int));
table.Columns.Add(columnName[4], typeof(int));
}
public static void printmark(DataTable t, int rowIndex, int columnIndex)
{
Console.WriteLine("Highest mark for " + t.Columns[columnIndex].ColumnName + ":");
Console.WriteLine("\tName: " + (string)t.Rows[rowIndex][0]);
Console.WriteLine("\tRole Number: " + (string)t.Rows[rowIndex][1]);
Console.WriteLine("\tMark: " + (int)t.Rows[rowIndex][columnIndex]);
}
}
}
它是如何工作的。我是否需要重構我的程序 – cjgeez
您想要查找每列的平均值,對不對?這個查詢計算給定'columnname' –
的平均值!你可以說得更詳細點嗎。由於我是C#的初學者,我無法找到需要插入此查詢的區域。如果可能,你可以在我的代碼中發送你的查詢。因爲我覺得很難實施。我會開始繼續下一個。謝謝 !! – cjgeez