简体   繁体   中英

Return an anonymous type as a strongly typed

I am writing a method in C# class. It is using Database Linq query. 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. Change select new to 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.

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 ). You can verify the type returned using intelisense by putting your cursor over .ToList() . 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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM