开发者

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 = s开发者_StackOverflow中文版tudent.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?


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
                  };


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().


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜