public Program()
{
List<Student> allStudent = new List<Student> {
new Student("张三",23),
new Student("李四",29),
new Student("王二",25),
new Student("赵六",26)
};
//Ling表达式
var stus1 = from s in allStudent
where s.Name == "王二"
select new { s.Name, s.Age };
//Lanmbda表达式
var stus2 = allStudent.Where(t => t.Name == "王二").Select(t => new { t.Name, t.Age });
}
public class Student { public string Name { set; get; } public int Age { set; get; } public Student(string name, int age) { this.Name = name; this.Age = age; } } Lambda确实比Linq表达式更加优雅 Linq表达式的select不能省略 //Linq var students1 = from t in db.Students where t.Name == “张三” select t; //Lambda var students2 = db.Students .Where(t => t.Name == “张三”);
Linq表达式必须需要括号包裹起来才能取结果集 //Linq var students1 = (from t in db.Students where t.Name == “张三” select t).ToList(); //Lambda var students2 = db.Students .Where(t => t.Name == “张三”) .ToList();
什么时候使用Linq? 通过上面的对比,好像Linq一文不值了。no,不是这样的。 比如下面几种情况我们就可以选择使用Linq: 例一:(本例适用于Linq to Object 和 没有建主外键的EF查询) Lambda中的Join需要传四个参数表达式,是不是有点晕了。。。