以下是在 lambda 中编写此查询的方法:
var customers = new List {
new Customer { CompanyId = “AC”, CustomerId = “Customer1” },
new Customer { CompanyId = “not-AC”, CustomerId = “Customer2” },
};
var userCustomers = new List {
new UserCustomer { CompanyId = “AC”, CustomerId = “Customer1”, User = “not-admin” },
new UserCustomer { CompanyId = “AC”, CustomerId = “Customer1”, User = “admin” },
new UserCustomer { CompanyId = “AC”, CustomerId = “Customer2”, User = “not-admin” },
new UserCustomer { CompanyId = “AC”, CustomerId = “Customer2”, User = “admin” },
new UserCustomer { CompanyId = “not-AC”, CustomerId = “Customer1”, User = “not-admin” },
new UserCustomer { CompanyId = “not-AC”, CustomerId = “Customer1”, User = “admin” },
new UserCustomer { CompanyId = “not-AC”, CustomerId = “Customer2”, User = “not-admin” },
new UserCustomer { CompanyId = “not-AC”, CustomerId = “Customer2”, User = “admin” }
};
使用查询表达式
var query =
from c in customers
join uc in userCustomers on
new { c.CompanyId, c.CustomerId } equals new { uc.CompanyId, uc.CustomerId }
where c.CompanyId == “AC” && uc.User == “admin“
select c;
使用 lambda 表达式
var lambda = customers.Where(c => c.CompanyId == “AC”) // inner sequence
.Join(userCustomers.Where(uc => uc.User == “admin”), // outer sequence
c => new { c.CompanyId, c.CustomerId }, // inner key selector
uc => new { uc.CompanyId, uc.CustomerId }, // outer key selector
(c, uc) => c);
两种方法产生相同的结果(客户的公司 ID 为“AC”,客户 ID 为“Customer1”),但如您所见,lambda 表达式更难编写和阅读!
希望这会有所帮助!