2013-03-12 118 views
2

我有這樣的查詢,返回我其useridaccess表和users用戶的名字,我要的是給我回誰在access不是用戶的那些userid拉姆達LINQ不加入C#

var query = db.Users 
     .Join(db.Access, c => c.UserId, o => o.UserId, 
     (c, o) => new { c.UserId, c.Name }); 

在SQL it'd是這樣的:

SELECT Users.Name 
FROM  Access INNER JOIN 
       Users ON Access.UserId <> Users.UserId 

什麼是lambda expression相當於SQL腳本?

回答

0
var exclude = db.Access.Select(p => p.UserId); 


var us = db.Users.Where(q => !exclude.Contains(q.UserId)).ToList(); 


ViewBag.UsersId = new SelectList(us, "UserId", "Name"); 

最後就是正確的答案,唯一不同的是在第一線。

謝謝大家!

6

使用Except

var res = db.Access.Except(query); 
0

您還可以使用! Contains()象下面這樣:

//Get Access user ids into an array 
var AccessUserIds = db.Access.Select(a => new {a.UserId}).ToArray(); 

//Users who are not in Access user id array 
var Results = db.Users.Where(u => !AccessUserIds.Contains(u.UserId));