I want to initialize var outside the foreach loop.
Here is my code:
public List<Course> GetCourse()
{
IList<Semester> semesters = Semester.Get();
foreach (Semester sm in semesters)
{
IList<CourseInstance> courseInstances = CourseInstance.Get(sm[0].SemesterId);
var courseInfos = from c in courseInstances
select new Course { Code = c.Course.Code, Name = c.Course.Name };
}
return courseInfos.ToList();
}
How do I initialize courseInfos out side the foreach loop? I try to initialize with null give me error!
EDIT:
If you want to map SemesterName to a list of courses, I would recommend a dictionary.
This will create a
Dictionary<string, List<Course>This is nearly identical to the code below, except that it maps the semester.Name as the key. This would, of course, mean you have to have unique semester names, otherwise the dictionary can’t be created.You are reinitializing courseInfos every time you loop in the foreach, so you will only get a list of the last semesterId.
You can write a linq query that does this all in one line for you.
To break it down,
does the same thing as the foreach. It will return an
IEnumerable<CourseInstance>.After that, you are calling
on the result that we got in the last section; it returns an
IEnumerable<Course>that you turn into a list.SelectMany works similar to Select except it will take each
IEnumerable<Course>and flatten it into one sequence instead ofIEnumerable<IEnumerable<Course>>