2011-03-24 53 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();