如何在foreach之外初始化var
我想在 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 初始化给我错误!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
var 从您初始化的值推断类型,因此使用 null 初始化永远不会起作用。其他一切都会。
我相信你想要的 Linq 语句是
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
编辑:
如果您想将 SemesterName 映射到课程列表,我会推荐一本字典。
这将创建一个
Dictionary
这与下面的代码几乎相同,只是它将 season.Name 映射为键。当然,这意味着您必须具有唯一的学期名称,否则无法创建词典。每次在 foreach 中循环时,您都会重新初始化 courseInfos,因此您只会获得最后一个学期 ID 的列表。
您可以编写一个 linq 查询,在一行中为您完成所有这些操作。
要分解它,
与 foreach 执行相同的操作。它将返回一个
IEnumerable
。之后,您调用
我们在上一节中得到的结果;它返回一个
IEnumerable
,您可以将其转换为列表。SelectMany 的工作方式与 Select 类似,只不过它会获取每个
IEnumerable
并将其展平为一个序列,而不是IEnumerable>
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>>
答案是:
但是,您将丢弃除
foreach
的最终迭代之外的所有内容。这是你想做的吗?The answer is:
However, you are discarding everything but the final iteration of the
foreach
. Is this what you meant to do?为什么不直接用第一个学期初始化 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?
可能是这个帮助。在每次迭代中收集课程信息。
may be this help. Collecting course info in each iteration.