Mahesh
Mahesh

Reputation: 1689

How to create list of anonymous types in select clause?

I am using LINQ to SQL for my database operations. Basically I have written a select query which returns a Student Type. one of the column in the student type is list of marks.

I am able to construct the anonymous student type without marks as given below:

var studentList = from student in context.Student
                  from marks in context.Marks.Where(m => m.studentId = studentId)
                  select new
                  {
                     RollNo = student.RollNo,
                     Name = student.Name,
                     PhoneNo = student.PhoneNo
                  };

Is there a possibility in LINQ to SQL to create a list of anonymous types(marks in this case) in my new anonymous type?

Upvotes: 1

Views: 1030

Answers (3)

Aducci
Aducci

Reputation: 26634

var studentList = (from student in context.Student
                  select new
                  {
                     RollNo = student.RollNo,
                     Name = student.Name,
                     PhoneNo = student.PhoneNo,
                     Marks = context.Marks.Where(m => m.studentId = student.studentId)
                  }).ToList();

Upvotes: 0

Jon
Jon

Reputation: 16718

If StudentId on your Marks table is a foreign key (and if not, why not?), you should just be able to do:

var studentList = (from student in context.Student
                   select new
                   {
                       student.RollNo, // no need to explicitly name the properties if they're the same name as the property you're selecting
                       student.Name,
                       student.PhoneNo,
                       student.Marks // LINQ to SQL will do the join automagically
                   }).ToList();

I'm also assuming you actually want a List<T> - to get one you need to call .ToList().

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532445

Selecting all student with marks I would think you would want to use a join. Edit: Oops, you probably only want one record per student. I've added a grouping.

var studentList = from student in context.Student
                  join marks in Context.Marks
                      on student.studentId equals marks.studentId
                  group by student
                  into g
                  select new
                  {
                      RollNo = g.Key.RollNo,
                      Name = g.Key.Name,
                      PhoneNo = g.Key.PhoneNo,
                      Marks = g.marks
                  };

Upvotes: 1

Related Questions