如何在foreach之外初始化var

发布于 2024-11-27 03:19:33 字数 600 浏览 1 评论 0 原文

我想在 foreach 循环之外初始化 var 。

这是我的代码:

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();
    }

如何在 foreach 循环之外初始化 courseInfos?我尝试用 null 初始化给我错误!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

再可℃爱ぅ一点好了 2024-12-04 03:19:33

var 从您初始化的值推断类型,因此使用 null 初始化永远不会起作用。其他一切都会。

我相信你想要的 Linq 语句是

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

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();
北笙凉宸 2024-12-04 03:19:33

编辑:

如果您想将 SemesterName 映射到课程列表,我会推荐一本字典。

 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())

这将创建一个 Dictionary 这与下面的代码几乎相同,只是它将 season.Name 映射为键。当然,这意味着您必须具有唯一的学期名称,否则无法创建词典。


每次在 foreach 中循环时,您都会重新初始化 courseInfos,因此您只会获得最后一个学期 ID 的列表。

您可以编写一个 linq 查询,在一行中为您完成所有这些操作。

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

要分解它,

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

与 foreach 执行相同的操作。它将返回一个 IEnumerable

之后,您调用

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

我们在上一节中得到的结果;它返回一个 IEnumerable,您可以将其转换为列表。

SelectMany 的工作方式与 Select 类似,只不过它会获取每个 IEnumerable 并将其展平为一个序列,而不是 IEnumerable>

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>>

浅忆流年 2024-12-04 03:19:33

答案是:

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();

但是,您将丢弃除 foreach 的最终迭代之外的所有内容。这是你想做的吗?

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?

瞎闹 2024-12-04 03:19:33

为什么不直接用第一个学期初始化 courseInfo 的第一个实例,然后迭代学期,是否有理由需要在 foreeach 之前初始化 courseInfo ?

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?

执笏见 2024-12-04 03:19:33

可能是这个帮助。在每次迭代中收集课程信息。

  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;
        }

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;
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文