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

Liam的C# 学习历程(六):LINQ(Language-INtegrated Query)

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

标签:

  在这一周的C#课程中,我们学习了一些在C#编程中需要用到的对数据库或XML文件进行处理的操作,这就是LINQ,它使得一种类似与我们在数据库中常用的SQL语言的查询语言成为了C#语言的一部分,方便了我们搜索数据库等方面的操作。下面我们就来一起复习一下。

  (一)创建LINQ(Creating the Query):

    1.From字句(The from clause):指定范围变量和数据源

from   customer  in customers
//customer:range variable from the data source.
//customers:Data source can be any collection that implements  System.Collections.Generic. IEnumerable<T>

    2.筛选(Filtering): 需要用到where字句,又被叫作筛选器

where  customer.FirstName == "Donna"
//筛选器是一个布尔表达式
where  customer.LastName.StartWith(“G”)
//You can also use composite expressions to construct more complex queries

    3.映射或选择(Projection):select字句,定义了如何返回结果。

select  customer;
//defines (or projects) the results.the query returns the customer objects.  

  (二)LINQ和C#:

    连接(Joining):

      在老师上课提到的MSDN上,我找到了一些简单的samples:

        1.Cross Join:

public void Linq102() 
{ 
  
    string[] categories = new string[]{  
        "Beverages",   
        "Condiments",   
        "Vegetables",   
        "Dairy Products",   
        "Seafood" };  
  
    List<Product> products = GetProductList(); 
  
    var q = 
        from c in categories 
        join p in products on c equals p.Category 
        select new { Category = c, p.ProductName }; 
 
    foreach (var v in q) 
    { 
        Console.WriteLine(v.ProductName + ": " + v.Category);  
    } 
}

        2.下面是一个使用到Group Join的例子:

public void Linq103() 
{ 
    string[] categories = new string[]{  
        "Beverages",  
        "Condiments",  
        "Vegetables",  
        "Dairy Products",  
        "Seafood" }; 
  
    List<Product> products = GetProductList(); 
  
    var q = 
        from c in categories 
        join p in products on c equals p.Category into ps 
        select new { Category = c, Products = ps }; 
  
    foreach (var v in q) 
    { 
        Console.WriteLine(v.Category + ":"); 
        foreach (var p in v.Products) 
        { 
            Console.WriteLine("   " + p.ProductName); 
        } 
    } 
}

        3.Cross Join with Group Join

public void Linq104() 
{ 
    string[] categories = new string[]{   
        "Beverages",  
        "Condiments",  
        "Vegetables", 
        "Dairy Products",   
        "Seafood" }; 
  
    List<Product> products = GetProductList(); 
  
  
  
    var q = 
        from c in categories 
        join p in products on c equals p.Category into ps 
        from p in ps 
        select new { Category = c, p.ProductName }; 
  
    foreach (var v in q) 
    { 
        Console.WriteLine(v.ProductName + ": " + v.Category); 
    } 
}

  仔细阅读面的代码,结合sample中所给的main函数,我们可以更好地理解join语句的一些用法,帮助我们更好地掌握LINQ语句。

Liam的C# 学习历程(六):LINQ(Language-INtegrated Query)

标签:

原文地址:http://www.cnblogs.com/tju-liuchang/p/4458535.html

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