开发者

How to initialize var outside foreach

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!


var infers the type from the value you are initialising with, so initialising with null will never work. Everything else will.

I believe the Linq statement you want is

var courses = semesters
    .SelectMany( s => CourseInstance.Get(s.SemesterId)
    .Select( c => new Course ( Code = c.Course.Code, Name = c.Course.Name ) )
    .ToList();


EDIT:

If you want to map SemesterName to a list of courses, I would recommend a dictionary.

 semesters.ToDictionary(semester => semester.Name, semester => 
                        semesters.SelectMany(sid => 
                                       CourseInstance.Get(sid.SemesterId))
                        .Select(c => new Course 
                        {Code = c.Course.Code, Name = c.Course.Name}).ToList())

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.

return semesters.SelectMany(sid => CourseInstance.Get(sid.SemesterId))
                           .Select(c => new Course { Code = c.Course.Code, 
                                           Name = c.Course.Name }).ToList()

To break it down,

.SelectMany(sid => CourseInstance.Get(sid.SemesterId)) 

does the same thing as the foreach. It will return an IEnumerable<CourseInstance>.

After that, you are calling

 .Select(c => new Course { Code = c.Course.Code, Name = c.Course.Name }) 

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 of IEnumerable<IEnumerable<Course>>


The answer is:

IEnumerable<Course> courseInfos = null;

foreach (Semester sm in semesters)
{
    IList<CourseInstance> courseInstances = CourseInstance.Get(semesters[0].SemesterId);
    courseInfos = from c in courseInstances
                  select new Course { Code = c.Course.Code, Name = c.Course.Name };
}
return courseInfos.ToList();

However, you are discarding everything but the final iteration of the foreach. Is this what you meant to do?


why not just initialize the first instance of courseInfo with the first semester and then iterate over Semesters, is there a reason you need to initialize courseInfo before the foreeach?


may be this help. Collecting course info in each iteration.

  public List<Course> GetCourse()
        {
        IList<Semester> semesters = Semester.Get();

        List<Course> courseInfos = new List<Course>();
        foreach (Semester sm in semesters)
            {
            IList<CourseInstance> courseInstances = CourseInstance.Get(sm.SemesterId);
            IEnumerable<Course> result = from c in courseInstances
                              select new Course { Code = c.Course.Code , Name = c.Course.Name };
            courseInfos.AddRange(result);
            }

        return courseInfos;
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜