2011-03-24 68 views
1

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

我能够构建无标记的匿名学生类型下面给出:

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到SQL的可能性在我的新创建匿名类型(在这种情况下标记)的列表匿名类型?

回答

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

如果StudentIdMarks表的外键(如果没有,为什么不呢?),你应该能够做到:

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

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