1.概要
如下两个语句
1.1.x.where(a=>a.id>5)
1.2 x.where(a=>{ return a.id>5;}) 报错(无法将具有语句体的lambda表达式转换为表达式树)
2.代码
public class LambdaTest
{
public class User {
public int Id { set; get; }
public string Name { set; get; }
public int CompanyId { set; get; }
}
public class Company {
public int Id { set; get; }
public string Name { set; get; }
}
public void mian() {
var users = new List<User> {new User() { Id = 1, Name = "zz", CompanyId = 1 },
new User() { Id = 2, Name = "fyh", CompanyId = 1 },
new User() { Id = 3, Name = "testuser", CompanyId = 2 },
new User() { Id = 4, Name = "entuser", CompanyId = 2 }
};
var companys = new List<Company>(){
new Company() {Id = 1,Name ="测试公司" },
new Company() {Id =2,Name ="上市公司" }
};
//操作一:数据在内存,可以随意操作
//下面主要看带有语句体的lambda表达式
var userCompanys = users.Join(companys, u => u.CompanyId, c => c.Id, (u, d) => {
var des = u.Name + d.Name;
Console.WriteLine(des);
return new { UserName = u.Name, CompanyName = d.Name, Des = des };
});
//操作二:数据在远端,不能随意操作
//这里我们用AsQueryable模拟数据在远端,下面这段会报错:无法将具有语句体的lambda表达式转换为表达式树;
/*
var userCompanys2 = users.AsQueryable().Join(companys.AsQueryable(), u => u.CompanyId, c => c.Id, (u, d){
var des = u.Name + d.Name;
Console.WriteLine(des);
return new { UserName = u.Name, CompanyName = d.Name, Des = des };
});
*/
}
}