If the data of
Tearchers
and
Classes
tables is read into the corresponding
DataTables
in the program, which may be preferable as these tables can be used for other purpose also, then a
DataTable
can be created with
TeacherId
in one column and all classes corresponding to each
TeacherId
in the
Classes
Column of the corresponding row as shown below:
void Main()
{
DataTable teachers = new DataTable();
teachers.Columns.Add("TeacherId",typeof(string),null);
teachers.Columns.Add("TeacherName",typeof(string),null);
teachers.Rows.Add("T1","Teacher1");
teachers.Rows.Add("T2","Teacher2");
DataTable classes = new DataTable();
classes.Columns.Add("ClassId",typeof(string),null);
classes.Columns.Add("TeacherId",typeof(string),null);
classes.Rows.Add("C1","T1");
classes.Rows.Add("C1","T2");
classes.Rows.Add("C4","T1");
classes.Rows.Add("C6","T2");
classes.Rows.Add("C7","T1");
classes.Rows.Add("C8","T1");
DataTable teacherClasses = new DataTable();
teacherClasses.Columns.Add("TeacherId",typeof(string),null);
teacherClasses.Columns.Add("Classes",typeof(string),null);
DataTable teacherClasses2 = teacherClasses.Clone();
teachers.AsEnumerable().Select (t => {
string teacherId = t.Field<string>("TeacherId");
string allClassIds = classes.AsEnumerable().Where (c => string.Equals(
c.Field<string>("TeacherId"),teacherId, StringComparison.InvariantCulture))
.Aggregate (string.Empty,(string allClasses, DataRow c) =>
allClasses + (string.IsNullOrEmpty(allClasses) ? string.Empty :
", ") + c.Field<string>("ClassId"));
teacherClasses.Rows.Add(teacherId,allClassIds);
return t;
}).Count();
foreach(DataRow tRow in teachers.Rows){
string teacherId= tRow["TeacherId"].ToString();
DataRow[] allClassRows = classes.Select(
string.Format("TeacherId='{0}'",teacherId),
string.Empty);
string allClassIds = string.Empty;
foreach(DataRow row in allClassRows)
allClassIds += (string.IsNullOrEmpty(allClassIds) ?
"" : ", ") + row["ClassId"].ToString();
teacherClasses2.Rows.Add(teacherId,allClassIds);
}
}
Then the
teacherClasses
can be assigned to the
DataSource
property of
DataGridview
.