我通常使用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();
非常感謝。
爲感謝 - 它的工作原理:-) –