gpt4 book ai didi

c# - 计算数据库中检索到的行

转载 作者:搜寻专家 更新时间:2023-10-30 20:19:34 25 4
gpt4 key购买 nike

Form1

我是 Visual C# 的新手,想知道如何计算从数据库中检索到的数据。

使用上面的 GUI,当点击“计算”时,程序将在 textBox1 中显示学生人数,在 textBox2 中显示所有学生的平均 GPA。

这是我的数据库表“Students”:

enter image description here

我能够显示学生人数,但我仍然对如何计算平均 GPA 感到困惑

这是我的代码:

    private void button1_Click(object sender, EventArgs e)
{
string connection = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Database1.accdb";
OleDbConnection connect = new OleDbConnection(connection);

string sql = "SELECT * FROM Students";
connect.Open();
OleDbCommand command = new OleDbCommand(sql, connect);
DataSet data = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.Fill(data, "Students");

textBox1.Text = data.Tables["Students"].Rows.Count.ToString();

double gpa;
for (int i = 0; i < data.Tables["Students"].Rows.Count; i++)
{
gpa = Convert.ToDouble(data.Tables["Students"].Rows[i][2]);
}

connect.Close();
}

最佳答案

您可以将 LINQ to DataTableAverage 一起使用方法:

var gpa = data.Tables["Students"].AsEnumerable()
.Average(row => row.Field<double>("GPA"));

关于c# - 计算数据库中检索到的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12880950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com