[英]Return an anonymous type as a strongly typed
I am writing a method in C# class. 我在C#类中编写一种方法。 It is using Database Linq query.
它正在使用Database Linq查询。 I want it's result to be returned by method.
我希望它的结果由方法返回。 I am using the following code but it is resulting in error;
我正在使用以下代码,但会导致错误;
class getCourses
{
public string Courseid { get; set; }
public string CourseName { get; set; }
}
public List<getCourses> GetCourses()
{
List<getCourses> L_courses = new List<getCourses>();
L_courses = (from Cr in _er.Courses
select new
{
Courseid = Cr.CourseID,
CourseName = Cr.CourseName,
}).ToList();
}
You are creating a list of anonymous types.You should create a strongly typed list which is List<getCourses>
according to your return type. 您正在创建一个匿名类型的列表。您
List<getCourses>
根据返回类型创建一个强类型的列表,即List<getCourses>
。 Change select new
to select new getCourses
. 更改
select new
以select new getCourses
。 Also creating another variable for list ( L_courses
) is completely unnecessary, you can just return the list directly if you are not planning to do anything with your list before return. 另外,完全不需要为列表(
L_courses
)创建另一个变量,如果您不打算在返回之前对列表做任何事情,则可以直接返回列表。
You have to tell it which class to use, not create an anonymous type: 您必须告诉它要使用哪个类,而不是创建匿名类型:
public List<getCourses> GetCourses()
{
return (from Cr in _er.Courses
select new getCourses
{
Courseid = Cr.CourseID,
CourseName = Cr.CourseName,
}).ToList();
}
Well 好
new {
Courseid = Cr.CourseID,
CourseName = Cr.CourseName, }
is an Anonymous type (just because the fields matches getCourses
doesn't mean it is a getCourses
). 是一个匿名类型(只是因为字段匹配
getCourses
并不意味着它是getCourses
)。 You can verify the type returned using intelisense by putting your cursor over .ToList()
. 您可以通过将光标放在
.ToList()
上来验证使用intelisense返回的类型。 You probably should use: 您可能应该使用:
new getCources() {
Courseid = Cr.CourseID,
CourseName = Cr.CourseName, }
Two answers. 两个答案。
First (piggy backing on other answers) you can write: 首先(小猪支持其他答案),您可以编写:
public List<getCourses> GetCourses() {
return _er.Courses.Select(c =>
new getCourses {
Courseid = c.CourseID,
CourseName = c.CourseName
}).ToList();
}
Second way... Since _er.Courses is already the object that you are wanting to deal with, why not something like this... Suppose _er.Courses is a list of Course objects. 第二种方式...因为_er.Courses已经是您要处理的对象,所以为什么不这样呢...假设_er.Courses是Course对象的列表。 Then you can do:
然后,您可以执行以下操作:
public Course : ICourseOverview {
// properties
}
public interface ICourseOverview {
public int CourseId { get; }
public string CourseName { get; }
}
Then you can simply do something like: 然后,您可以简单地执行以下操作:
public IEnumerable<ICourseOverview> GetCourses() {
return (IEnumerable<ICourseOverview>)_er.Courses;
}
But if you did that, then it is debatable what the point of this class is (depending on the scope that the application has on _er and _er.Courses). 但是,如果您这样做了,那么此类的重点是有争议的(取决于应用程序对_er和_er.Courses的范围)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.