2014-04-06 87 views
2

我通常使用lambda表示法進行選擇,但對連接感到沮喪。我使用LINQPad爲自己設定了一個簡單的練習。 LINQ查詢是:手動將LINQ查詢語法轉換爲Lambda表示法

List<int> allStudents = new List<int> {1,2,3,4,5,6,7,8,9}; 
List <int> studentsIdList = new List<int> {1,3,5,7,9}; 

var q = 
     from c in allStudents 
     join p in studentsIdList on c equals p into ps 
     from p in ps.DefaultIfEmpty() 
     where p == 0 
     select new { Student = c}; 


q.Dump(); 

它產生預期的結果集2,4,6,8

然而,當我把它寫在lambda符號爲:

List<int> allStudents = new List<int> {1,2,3,4,5,6,7,8,9}; 
List <int> studentsIdList = new List<int> {1,3,5,7,9}; 

var q = 
     allStudents 
     .GroupJoin(
        studentsIdList, 
        m => allStudents, 
        n => studentsIdList, 
        (m, n) => new {allS = m, excS = n.DefaultIfEmpty(0)}) 
     .Where(x => x.excS.SingleOrDefault() == 0) 
     .Select (x => x.allS); 

q.Dump(); 

我得到一個結果集的1,2,3,4,5,6,7,8,9

和LINQPad不顯示拉姆達轉換。

兩個問題:

  • 有什麼不對我的拉姆達查詢?
  • 如何獲得LINQPad以顯示lambda翻譯?

UPDATE

使用下面的回答,我能夠糾正我嘗試

List<int> allStudents = new List<int> {1,2,3,4,5,6,7,8,9}; 
List <int> studentsIdList = new List<int> {1,3,5,7,9}; 

var q = allStudents 
    .GroupJoin(studentsIdList, 
     a => a, b => b, 
     (a, b) => new { Id = a, Present = b.DefaultIfEmpty() }) 
    .Where(x => x.Present.Single() == 0) 
    .Select(x => x.Id); 

q.Dump(); 

非常感謝。

回答

2

這是你如何寫聯接:

var q = allStudents 
    .GroupJoin(studentsIdList, a => a, b => b, (a, b) => new { Id = a, Present = b }) 
    .Where(join => !join.Present.Any()) 
    .Select(join => join.Id); 

當然,對於這種非常情況下,使用Except就會簡單得多。

不能幫助Linqpad的問題,因爲我不使用它自己。

3

第二個問題的答案是在您的源代碼集上調用.AsQueryable()。這使得LINQPad顯示C#的翻譯成lambda語法:

List<int> allStudents = new List<int> {1,2,3,4,5,6,7,8,9}; 
List <int> studentsIdList = new List<int> {1,3,5,7,9}; 
var q = from c in allStudents.AsQueryable() 
     join p in studentsIdList on c equals p into ps 
     from p in ps.DefaultIfEmpty() 
     where p == 0 
     select new { Student = c}; 

q.Dump(); 
+0

爲感謝 - 它的工作原理:-) –

相關問題