Saturday 3 March 2012

C# - How to Create anonymous types

This example shows the difference between anonymous types vs full types
           // this example will show difference between full types and anonymous types
            // I am using 2 tables for this purpose: course and department
            // 1 department may have 0, 1 or more courses
            // here is the first example of a query that loads data into full type object

            using (SchoolEntities schoolContext = new SchoolEntities())
            {
                var courseQuery = from c in schoolContext.Course
                                  orderby c.CourseID
                                  select c;
                // example above will load all fields from course table

                var courseQuery2 = from c in schoolContext.Course
                                   orderby c.CourseID
                                   select new { c.CourseID, c.Title };
                // example above will create new anonymous type with CourseId and Title

                // as mentioned before, 1 department may have 0, 1, or more courses
                // now I create anonymous type that will load course info with corresponding department information

                var courseQuery3 = from c in schoolContext.Course
                                   orderby c.CourseID
                                   select new { c.CourseID, c.Title, c.Department.Name };



No comments:

Post a Comment