Take a look at below example:
void Main()
{
List<Student> StudentData= new List<Student>{
new Student(){Id = 1, Name = "John", CourseName = "Math", CourseStatus ="Complete"},
new Student(){Id = 1, Name = "John", CourseName = "Science", CourseStatus ="In Complete"},
new Student(){Id = 1, Name = "John", CourseName = "English", CourseStatus ="Complete"},
new Student(){Id = 2, Name = "Sarah", CourseName = "Math", CourseStatus ="Complete"},
new Student(){Id = 2, Name = "Sarah", CourseName = "Computer", CourseStatus ="Complete"},
new Student(){Id = 3, Name = "John Doe", CourseName = "Account", CourseStatus ="Complete"},
};
List<Studentv2> result = StudentData
.GroupBy(x => x.Id)
.Select(grp => new Studentv2()
{
StudentId = grp.Key,
StudentName = grp.Select(x => x.Name).First(),
Courses = grp.Select((x,y) => new Course
{
CourseId = y+1,
CourseName = x.CourseName,
CourseStatus = x.CourseStatus
}).ToList()
})
.ToList();
}
public class Student
{
public int Id=0;
public string Name = string.Empty;
public string CourseName = string.Empty;
public string CourseStatus = string.Empty;
}
public class Studentv2
{
public int StudentId=0;
public string StudentName = string.Empty;
public List<Course> Courses = null;
}
public class Course
{
public int CourseId = 0;
public string CourseName = string.Empty;
public string CourseStatus = string.Empty;
}
Good luck!