码迷,mamicode.com
首页 > Windows程序 > 详细

C#学习记录(七)LINQ语句及LAMDA表达式

时间:2015-04-26 22:47:44      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

LINQ

LINQ是一种集成在计算机语言里的信息查询语句,可以让编写者以代码的方式操作数据库。

在C#中,LINQ语句有两种写法。

这是第一种写法

IEnumerable<Customer> result =  from   customer in customers
      where  customer.FirstName == "Donna“  
      select customer;

由于这种写法比较容易和SQL语言混淆,所以我更倾向于使用另一种写法

IEnumerable<Customer> result =  
    customers.Where(customer => customer.FirstName == "Donna")
    .Select(customer => customer);

这种写法和C#语句的语法相近,并且同样易于理解,所以在我之前编写ASP.net网页时便使用这一种写法。

在Where和Select后面填入的是Lamda语句,这种语句是Delegate的简化,有利于提升代码的阅读性。

Lamda表达式的形式通常是这样的

student => student.Age < 17

第一个student指的是传入的参数, =>是Lamda表达式的特定符号,右边是一个表达式,在查询语句中,此符号后面的表达式返回值通常是布尔类型的。例如上面这条语句放在Where中可以筛选出年龄小于十七岁的学生。

 

我编写了一个带数据库的简单网页来测试LINQ语句的使用,网页使用MVC4模板

这是存储学生信息的Model

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public int Height { get; set; }
    }

这个Context用于连接数据库

    public class StudentContext : DbContext
    {
        public DbSet<Student> Students { get; set; }
    }

这是用于数据库初始化的类

    public class StudentContextInitializer : DropCreateDatabaseAlways<StudentContext>
    {
        protected override void Seed(StudentContext context)
        {
            context.Students.Add(
                    new Student() { Id = 1, Name = "Bob", Age = 12, Height = 125 }
                );
            context.Students.Add(
                    new Student() { Id = 2, Name = "Andy", Age = 10, Height = 111 }
                );
            context.Students.Add(
                    new Student() { Id = 3, Name = "Cooler", Age = 17, Height = 165 }
                );
            context.Students.Add(
                    new Student() { Id = 4, Name = "Vv", Age = 16, Height = 171 }
                );
            context.SaveChanges();
        }
    }

数据库初始化还需要在Application_Start()中有以下语句

Database.SetInitializer<StudentContext>(new StudentContextInitializer());

这是在HomeController中的LINQ语句测试

        public ActionResult Index()
        {
            StudentContext db = new StudentContext();
            var students = db.Students.Where(Student => Student.Age < 15).ToList();
            ViewBag.Message = "\n";
            foreach (var student in students)
            {
                ViewBag.Message += student.Name;
                ViewBag.Message += "\n";
            }

            return View();
        }

输出结果(模板懒得改了将就着看看吧)

技术分享

 

C#学习记录(七)LINQ语句及LAMDA表达式

标签:

原文地址:http://www.cnblogs.com/zany/p/4458524.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!