这里有一些东西可以给你一个想法:
using System;
using System.Data;
using System.Collections.Generic;
namespace SO17416111
{
class Class
{
public int Id { get; set; }
public string Name { get; set; }
}
// Note that definition of Class and Student only differ by name
// I'm assuming that Student can/will be expanded latter.
// Otherwise it's possible to use a single class definition
class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main()
{
DataTable table = GetData();
Dictionary<Class, List<Student>> d = new Dictionary<Class, List<Student>>();
foreach (DataRow dr in table.Rows)
{
// If it's possible to get null data from the DB the appropriate null checks
// should also be performed here
// Also depending on actual data types in your DB the code should be adjusted as appropriate
Class key = new Class {Id = (int) dr["ClassID"], Name = (string) dr["ClassName"]};
Student value = new Student { Id = (int)dr["StudentID"], Name = (string)dr["StudentName"] };
if (!d.ContainsKey(key))
{
d.Add(key, new List<Student>());
}
d[key].Add(value);
}
foreach (var s in d.Keys)
{
foreach (var l in d[s])
{
Console.Write(s.Id + "-" + s.Name + "-" + l.Id + "-" + l.Name + "\n");
}
}
}
// You don't need this just use your datatable whereever you obtain it from
private static DataTable GetData()
{
DataTable table = new DataTable();
table.Columns.Add("ClassID", typeof (int));
table.Columns.Add("ClassName", typeof (string));
table.Columns.Add("StudentID", typeof (int));
table.Columns.Add("StudentName", typeof (string));
table.Rows.Add(1, "A", 1000, "student666");
table.Rows.Add(2, "B", 1100, "student111");
table.Rows.Add(5, "C", 1500, "student777");
table.Rows.Add(1, "A", 1200, "student222");
table.Rows.Add(2, "B", 1080, "student999");
return table;
}
}
}
请注意,这可以作为控制台应用程序进行编译和测试 - 我Response.Write
用Console.Write
. 我还在生成一个测试数据表,您应该能够使用您的应用程序中已经存在的数据表。就班级/学生班级而言,您有几个选择:您可以有两个单独的班级,如我所展示的,您可以使用同一个班级,甚至可以使用元组班级。我建议您使用两个单独的类,因为它提高了可读性和可维护性。
请注意,如果您只需要输出它们,则不需要字典或任何类似的东西:
// Add null checks and type conversions as appropriate
foreach (DataRow dr in table.Rows)
{
Response.Write(dr["ClassID"] + "-" + dr["ClassName"] + "-" + dr["StudentID"] + "-" + dr["StudentName"] + "<br>");
}