【发布时间】:2015-10-14 14:43:27
【问题描述】:
我的 ClassGrades 表包含以下字段:
Id、ClassId、Student、Match、Science、History、English
我使用如下函数检索所有正确的行:
IList<ClassGrade> classGrades = ClassService.GetClassGrades(classId: 1);
此列表中的 ClassGrade 对象如下所示:
Id=1,ClassId=1,学生='Mark',数学=50.6,科学=21.8,历史=70.7,英语=80.1
Id=2,ClassId=1,学生='Jacob',数学=70.8,科学=19.4,历史=78.7,英语=11.1
Id=3,ClassId=1,学生='Lauren',数学=21.9,科学=61.1,历史=99.5,英语=12.1
Id=4,ClassId=1,Student='Sarah',Math=81.7,Science=65.2,History=73.7,English=65.1
我需要翻转这些结果,以便学生是列,带有成绩的科目是行,然后将其绑定到我页面上的网格。 我认为创建一个新的数据表并根据需要对其进行自定义是最好的方法。
DataTable dt = new DataTable();
最后我的网格需要看起来像这样:
Mark Jacob Lauren Sarah
Math 50.6 70.8 21.9 81.7
Science 21.8 19.4 61.1 65.2
History 70.7 78.7 99.5 73.7
English 80.1 11.1 12.1 65.1
谁能给我一个示例,说明我将如何获取 ClassGrades 的对象列表并动态创建类似于上述的数据表。 我宁愿尽可能使用 linq。另外,如果完全在 sql 中执行此操作是首选方式,我也可以,但举个例子就好了。
需要注意的几点:
- 主题永远只是那 4 个。
- 学生可以是任意随机数量,具体取决于班级中有多少学生。
- 为班级中的每个学生返回一行。
以下是我遇到问题的示例:
// retrieve object list
IList<ClassGrade> classGrades = ClassService.GetClassGrades(classId: 1);
// create datatable
DataTable dt = new DataTable();
// get list of students
var students = from s in classGrades
select s.Student
// get list of subjects
IList<string> subjects = new List<string>() { "Math", "Science", "History", "English" };
// create columns
table.Columns.Add(subject, typeof(string));
foreach (var student in students)
{
table.Columns.Add(student, typeof(double));
}
// create rows
foreach (var subject in subjects)
{
row = dt.NewRow();
row[subject] = subject;
foreach (var classGrade in classGrades)
{
// this is where I get stuck
row[classGrade.Student] =
}
}
【问题讨论】:
-
您可能认为这毫无意义,但请分享您拥有的和产生的东西。
-
我添加了一个我正在尝试做的示例。
标签: c# sql linq datatable datasource