如何在select子句中创建匿名类型列表?

时间:2011-03-24 17:06:27

标签: c# sql linq

我正在使用LINQ to SQL进行数据库操作。基本上我写了一个返回学生类型的选择查询。学生类型中的一列是标记列表。

我可以构建没有标记的匿名学生类型,如下所示:

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

LINQ to SQL是否有可能在我的新匿名类型中创建匿名类型列表(本例中为标记)?

3 个答案:

答案 0 :(得分:1)

选择所有带标记的学生我认为你会想要使用连接。 编辑:糟糕,您可能只想要每位学生一条记录。我添加了一个分组。

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

答案 1 :(得分:0)

如果StudentId表上的Marks是外键(如果不是,为什么不呢?),您应该能够做到:

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

我还假设你真的需要List<T> - 来获得一个你需要致电.ToList()的人。

答案 2 :(得分:0)

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();
相关问题