Hi I have a web application in mvc in which i have teacher and courses , as well as teacherVsCourses Table , in teachervscourses table i am saving assigned courses to each teacher , right now I have a teacher for which i have assigned five courses to him and in db i have five rows , I want it to be one row with teacher name and five courses with comma separated list.
<pre> public ActionResult Index(string sortOrder, string currentFilter, string SearchString, int? page)
{
ViewBag.Course_Id = _ITeacherCoruses.PopulateCourses();
ViewBag.Teacher_Id = _ITeacherCoruses.PopulateTeachers();
ViewBag.Semester_Id = _ITeacherCoruses.PopulateSemsters();
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
if (SearchString != null)
{
page = 1;
}
else
{
SearchString = currentFilter;
}
ViewBag.CurrentFilter = SearchString;
var dept = from s in db.Teacher_courses
select s;
dept =dept.Include(t => t.course).Include(t => t.regs).Include(t => t.semesterName).OrderBy(t => t.Teacher_Id);
if (!String.IsNullOrEmpty(SearchString))
{
dept = dept.Where(s => s.course.Course_Name.Contains(SearchString));
}
switch (sortOrder)
{
case "name_desc":
dept = dept.OrderByDescending(s => s.course.Course_Name);
break;
case "Date":
dept = dept.OrderBy(s => s.Course_Assignment_date);
break;
case "date_desc":
dept = dept.OrderByDescending(s => s.Course_Assignment_date);
break;
default:
dept = dept.OrderBy(s => s.course.Course_Name);
break;
}
int pageSize = 5;
int pageNumber = (page ?? 1);
dept = dept.Include(t => t.course).Include(t => t.regs).Include(t => t.semesterName).OrderBy(t => t.Teacher_Id);
return View(productsArray.ToPagedList(pageNumber, pageSize));
}
What I have tried:
I have grouped the record but do not know how to use it on view , from below user mean the teacher and hobby means the courses
<pre> Teacher_courses[] productsArray = dept.ToArray();
var groupedUsers = from u in productsArray
group u by u.regs.FirstName into g
select new
{
Name = g.First<Teacher_courses>().Teacher_Id,
Hobby = g.Select(u => u.Course_Id)
};
foreach (var user in groupedUsers)
{
Console.WriteLine("Teacher_ID: {0}", user.Name);
foreach (var hobby in user.Hobby)
{
Console.WriteLine("Course_ID: {0}", hobby);
}
}