[英]Cannot implicitly convert type Generic List to Class
I want to list courses and list semesters for every course. 我想列出课程并列出每门课程的学期。
Here is my code 这是我的代码
public List<Course> GetAllCourses()
{
IList<App> app = App.GetAll();
List<CInstance> ci = new List<CInstance>();
for (int i = 0; i < app.Count; i++)
{
ci.Add(CInstance.GetInstance(app[i].Id));
}
return ci.Select(c => new Course
{
CourseId = c.Course.CourseId,
Semester = ci.Select(s => new Semester
{
SemesterId = c.Course.Semester.SemesterId
}).ToList()
}).ToList();
}
I get Cannot implicitly convert type System.Collection.Generic.List<Test.Semester>
to Test.Semester
我无法将类型
System.Collection.Generic.List<Test.Semester>
隐式转换为Test.Semester
Can someone please correct this code for me? 有人可以为我更正此代码吗?
Update 更新资料
I'm exporting to JSON. 我正在导出到JSON。 So, it will be look like this
所以,看起来像这样
[
- {
courseId: 123,
courseName: "someCouse",
semester:
- {
semesterId:26
},
- {
semesterId:27
}
}
]
您尚未显示代码,但我认为您的Semester
属性为Test.Semester
类型,其中应为List<Semester>
类型(或更好的IList<Semester>
)。
Depends on what you're trying to do. 取决于您要执行的操作。 If it would only have a single semester, instead of
如果只有一个学期,而不是
Semester = ci.Select(s => new Semester
{
SemesterId = c.Course.Semester.SemesterId
}).ToList()
You could use FirstOrDefault() like 您可以像这样使用FirstOrDefault()
Semester = ci.FirstOrDefault(s => new Semester
{
SemesterId = c.Course.Semester.SemesterId
})
If it's possible that it's in more than 1 semester, you'll need to change your Semester type to be a list. 如果有可能超过一个学期,则需要将您的学期类型更改为列表。
If you want to get a proper JSON-document with an array of Semester
you'll have to edit the Course
-class, so that the property Semester
is a List<Semester>
instead of Semester
. 如果要获取带有
Semester
数组的正确的JSON文档,则必须编辑Course
类,以便属性Semester
是List<Semester>
而不是Semester
。
Example: 例:
public class Course
{
public int CourseID { get; set; }
public string CourseName { get; set; }
public List<Semester> Semester { get; set; }
}
If your Course
-class looks like that, you should be able to run the rest of your function without any changes. 如果您的
Course
类看起来像这样,那么您应该能够运行其余功能,而无需进行任何更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.