using System.Collections;
using System.Collections.Generic;
public static void Main()
var list = new List<Course>();
list.Add(new Course { Id = 1 });
list.Add(new Course { Id = 2, RequiredCourse = "3" });
list.Add(new Course { Id = 3, RequiredCourse = "4" });
list.Add(new Course { Id = 4 });
list.Add(new Course { Id = 5 });
list.Add(new Course { Id = 6 });
list.Add(new Course { Id = 7 });
list.Add(new Course { Id = 8, RequiredCourse = "10" });
list.Add(new Course { Id = 9 });
list.Add(new Course { Id = 10 });
list = list.OrderBy(i => i.Id).ThenBy(i => i.RequiredCourse).ToList();
var copy = new List<Course>();
populateParent(list,ref copy, tt);
if(!copy.Any(p => p.Id == tt.Id))
Console.WriteLine(tt.Id + " " + tt.RequiredCourse);
public static Course populateParent(List<Course> inputList,ref List<Course> outputList, Course current)
if(string.IsNullOrWhiteSpace(current.RequiredCourse))
if(!outputList.Any(p => p.Id == current.Id))
var tt = inputList.First(p => current.RequiredCourse != null && p.Id == int.Parse(current.RequiredCourse) );
var parent = populateParent(inputList,ref outputList,tt);
if(!outputList.Any(p => p.Id == parent.Id))
if(!outputList.Any(p => p.Id == tt.Id))
public string RequiredCourse;