LINQ,语言集成查询(Language Integrated Query)是一组用C#和Visual Basic语言的扩展。

对于编写查询的开发人员来说,LINQ 最明显的“语言集成”部分是查询表达式。查询表达式是使用 C# 3.0 中引入的声明性查询语法编写的。通过使用查询语法,你甚至可以使用最少的代码对数据源执行复杂的筛选、排序和分组操作。你使用相同的基本查询表达式模式来查询和转换 SQL 数据库、ADO.NET 数据集、XML 文档和流以及 .NET 集合中的数据。

下面我们通过一些实际中常用的功能举例来学习一下。

1.简单数组的一些基本操作

查询数组中大于80的分数。

             int[] scores = new int[] { , , ,  };

             IEnumerable<int> scoreQuery = from score in scores
where score >
select score;
6
foreach(int score in scoreQuery)
{
Console.WriteLine(score);
}

查询数组中大于80的分数,按照升序ascending排列(默认为降序descending ),并且格式化结果。

             int[] scores = new int[] { , , ,  };

             IEnumerable<string> scoreQuery = from score in scores
where score >
orderby score ascending
select String.Format("Score: {0}",score); foreach(string score in scoreQuery)
{
Console.WriteLine(score);
}

2.数组列表的一些基本操作
这里首先创建一个程序员Programer类,包含了ID,Name,Age,Language属性。

     public class Programer
{
public int ID;
public string Name;
public int Age;
public string Language;
}

where

然后创建一个Programer类型的测试数组列表。查找编程语言使用C#的程序员。结果将输出Name1Name4

             Programer[] programers = new Programer[]{
new Programer{ID=,Name="Name1",Age=,Language="C#"},
new Programer{ID=,Name="Name2",Age=,Language="Visual Basic"},
new Programer{ID=,Name="Name3",Age=,Language="C++"},
new Programer{ID=,Name="Name4",Age=,Language="C#"},
new Programer{ID=,Name="Name5",Age=,Language="C"}
}; IEnumerable<Programer> programerQuery =
from p in programers
where p.Language == "C#"
select p; foreach(var item in programerQuery)
{
Console.WriteLine(item.Name);
}

where / orderby / select格式化数据

同样,这里也可以根据需要进行排序,对结果格式化等操作。下面查找编程语言使用C#的程序员,按Age升序排列,结果格式化输出NameAge

             Programer[] programers = new Programer[]{
new Programer{ID=,Name="Name1",Age=,Language="C#"},
new Programer{ID=,Name="Name2",Age=,Language="Visual Basic"},
new Programer{ID=,Name="Name3",Age=,Language="C++"},
new Programer{ID=,Name="Name4",Age=,Language="C#"},
new Programer{ID=,Name="Name5",Age=,Language="C"}
}; IEnumerable<string> programerQuery =
from p in programers
where p.Language == "C#"
orderby p.Age ascending
select String.Format("Name: {0} , Age: {1}", p.Name, p.Age); foreach(var item in programerQuery)
{
Console.WriteLine(item);
}

select部分数据

对于查询的结果,我们还可以根据需要选取部分数据。下面我们只需要程序员列表中的NameLanguage数据。

             Programer[] programers = new Programer[]{
new Programer{ID=,Name="Name1",Age=,Language="C#"},
new Programer{ID=,Name="Name2",Age=,Language="Visual Basic"},
new Programer{ID=,Name="Name3",Age=,Language="C++"},
new Programer{ID=,Name="Name4",Age=,Language="C#"},
new Programer{ID=,Name="Name5",Age=,Language="C"}
}; var newProgramers = from p in programers
select new
{
Name = p.Name,
Language = p.Language
}; foreach(var item in newProgramers)
{
Console.WriteLine("Name: {0} , Language: {1}", item.Name, item.Language);
}

group

当我们需要知道每种编程语言都有哪些程序员,我们就需要用到group分组功能。

             Programer[] programers = new Programer[]{
new Programer{ID=,Name="Name1",Age=,Language="C#"},
new Programer{ID=,Name="Name2",Age=,Language="Visual Basic"},
new Programer{ID=,Name="Name3",Age=,Language="C++"},
new Programer{ID=,Name="Name4",Age=,Language="C#"},
new Programer{ID=,Name="Name5",Age=,Language="C"}
}; var programerGroupByLanguage = from p in programers
group p by p.Language; foreach (var group in programerGroupByLanguage)
{
Console.WriteLine("Group: {0}", group.Key);
foreach(var item in group)
{
Console.WriteLine(item.Name);
}
Console.WriteLine();
}

group into
当我们想计算有多少程序员知道某种开发语言。在使用group 子句对开发语言进行分组后,可以使用Into子句将group 的子句结果存储在临时变量中。之后可以使用此变量来执行其他查询。

             Programer[] programers = new Programer[]{
new Programer{ID=,Name="Name1",Age=,Language="C#"},
new Programer{ID=,Name="Name2",Age=,Language="Visual Basic"},
new Programer{ID=,Name="Name3",Age=,Language="C++"},
new Programer{ID=,Name="Name4",Age=,Language="C#"},
new Programer{ID=,Name="Name5",Age=,Language="C"}
}; var programerGroupByLanguage = from p in programers
group p by p.Language into languageGroup
select new
{
Language = languageGroup.Key,
Count = languageGroup.Count()
}; foreach (var group in programerGroupByLanguage)
{
Console.WriteLine("Language {0} have {1} programers", group.Language, group.Count);
}

3.多个数组列表的一些基本操作

创建两个类,Product产品类和Category类别类,每个产品分配一个类别。

     public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
} public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public int CategoryID { get; set; }
public string Description { get; set; }
}

接着创建一些Category类型和Product类型的测试数组列表。

from...from / from...join..on

下面我们按类别查询所有产品。

             Category[] categories = new Category[]{
new Category{CategoryID=,CategoryName="TOYOTA"},
new Category{CategoryID=,CategoryName="BMW"},
new Category{CategoryID=,CategoryName="BENZ"},
new Category{CategoryID=,CategoryName="HONDA"},
new Category{CategoryID=,CategoryName="LEXUS"}
}; Product[] products = new Product[]{
new Product{ProductID=,ProductName="Car1",CategoryID=,Description="TOYOTA Car"},
new Product{ProductID=,ProductName="Car2",CategoryID=,Description="TOYOTA SUV"},
new Product{ProductID=,ProductName="Car3",CategoryID=,Description="BMW Car"},
new Product{ProductID=,ProductName="Car4",CategoryID=,Description="BMW SUV"},
new Product{ProductID=,ProductName="Car5",CategoryID=,Description="BENZ Car"},
new Product{ProductID=,ProductName="Car6",CategoryID=,Description="HONDA Car"},
new Product{ProductID=,ProductName="Car7",CategoryID=,Description="LEXUS Car"},
new Product{ProductID=,ProductName="Car8",CategoryID=,Description="LEXUS SUV"}
}; var productByCategoryResult1 = from c in categories
join p in products
on c.CategoryID equals p.CategoryID
select new
{
c.CategoryName,
p.ProductName,
p.Description
}; var productByCategoryResult2 = from c in categories
from p in products
where c.CategoryID ==p.CategoryID
select new
{
c.CategoryName,
p.ProductName,
p.Description
}; Console.WriteLine("Result 1:");
foreach(var item in productByCategoryResult1)
{
Console.WriteLine(item);
} Console.WriteLine("Result 2:");
foreach (var item in productByCategoryResult2)
{
Console.WriteLine(item);
}

我们看到使用多个from和使用join查询出的结果是一样的。

分组into

当我们需要统计每种类别下的产品时,也就是对类别进行分组,只需加上into到某个变量语句即可,此时这个变量将自动对产品的结果集进行分组。

             var productByCategoryResult = from c in categories
join p in products
on c.CategoryID equals p.CategoryID
into CategoryProducts
select new
{
c.CategoryName,
Products=CategoryProducts
}; foreach (var item in productByCategoryResult)
{
Console.WriteLine("Category: {0}",item.CategoryName);
foreach(var product in item.Products)
{
Console.WriteLine("{0} ({1})", product.ProductName, product.Description);
}
}

let

如果要将子表达式的结果存储在变量中以便来执行其他操作,可以使用Let子句。例如这里需要统计分配给类别的产品数量。

              var productByCategoryResult = from c in categories
join p in products
on c.CategoryID equals p.CategoryID
into CategoryProducts
let productCount=CategoryProducts.Count()
select new
{
c.CategoryName,
Count=productCount
}; foreach (var item in productByCategoryResult)
{
Console.WriteLine("Category {0} have {1} products", item.CategoryName, item.Count);
}

好了,本篇就先到此,希望对你有所帮助,谢谢!

LINQ查询表达式基础的更多相关文章

  1. LINQ查询表达式(1) - 查询表达式基础

    LINQ包括五个部分:LINQto Objects.LINQ to DataSets.LINQ to SQL.LINQ to Entities.LINQ to XML. 什么是查询?它有什么用途? “ ...

  2. Linq专题之创建Linq查询表达式

    本节我们主要介绍一下如何创建查询集合类型,关系数据库类型,DataSet对象类型和XML类型的数据源的Linq查询表达式. 下面在实例代码ReadyCollectionData()函数创建了准备的数据 ...

  3. 2.3 LINQ查询表达式中 使用select子句 指定目标数据

    本篇讲解LINQ查询的三种形式: 查询对象 自定义查询对象某个属性 查询匿名类型结果 [1.查询结果返回集合元素] 在LINQ查询中,select子句和from子句都是必备子句.LINQ查询表达式必须 ...

  4. LINQ查询表达式---------let子句

    LINQ查询表达式---------let子句 let子句创建一个范围变量来存储结果,变量被创建后,不能修改或把其他表达式的结果重新赋值给它.此范围变量可以再后续的LINQ子句中使用. class P ...

  5. LINQ查询表达式---------join子句

    LINQ查询表达式---------join子句 join 子句接受两个源序列作为输入. 每个序列中的元素都必须是可以与另一个序列中的相应属性进行比较的属性,或者包含一个这样的属性. join子句使用 ...

  6. LINQ查询表达式---------orderby子句

    LINQ查询表达式---------orderby子句 LINQ可以按元素的一个或多个属性对元素进行排序. class Program { public class PerInfo { public ...

  7. LINQ查询表达式---------into

    LINQ查询表达式---------into into 上下文关键字创建一个临时标识符,以便将 group.join 或 select 子句的结果存储到新的标识符 class Program { pu ...

  8. LINQ查询表达式---------group子句

    LINQ查询表达式---------group子句 LINQ表达式必须以from子句开头,以select或group子句结束.使用guoup子句来返回元素分组后的结果.group 子句返回一个 IGr ...

  9. LINQ查询表达式---------select子句

    LINQ查询表达式---------select子句 1.1常见的select子句查询 class Program { public class PerInfo { public int Id { g ...

随机推荐

  1. Solr 按照得分score跟指定字段相乘排序

    sort=product([you_field],query($q)) desc

  2. Android学习笔记--处理UI事件

    Handling UI Events 在Android里, 有不只一种方式可以截获用户与你的应用程序交互的事件. 在你的界面上处理事件时,你需要捕获用户与某个View实例交互时所产生的事件.View类 ...

  3. C#生成随机验证吗例子

    C#生成随机验证吗例子: public class ValidateCode : IHttpHandler, IRequiresSessionState { HttpContext context; ...

  4. java的HashCode和equals

    什么时候用到hashcode,什么时候用到equals? 首先java为每个对象都生成有默认的hashcode,这个java core里说是java对象的内存地址,但是equals方法里比较的也是对象 ...

  5. scrapy setting 备注

    scrapy 脚本里面设置输出文件: process = CrawlerProcess(settings) process.settings.set('FEED_URI', 'wangyi.csv', ...

  6. Python3基础 add() 向集合中加入新的元素

    镇场诗: 诚听如来语,顿舍世间名与利.愿做地藏徒,广演是经阎浮提. 愿尽吾所学,成就一良心博客.愿诸后来人,重现智慧清净体.-------------------------------------- ...

  7. python中numpy对函数进行矢量化转换

    在对numpy的数组进行操作时,我们应该尽量避免循环操作,尽可能利用矢量化函数来避免循环. 但是,直接将自定义函数应用在numpy数组之上会报错,我们需要将函数进行矢量化转换. def Theta(x ...

  8. CSS文字大小单位PX、EM、PT

    老是被人问到px.pt和em的区别,自己有时候也会纠结到底该用什么单位,今天特意查了一些文章,下面这篇虽然很久远了,但解释的比较全面,转载收藏之.点击查看原文 这里引用的是Jorux的"95 ...

  9. TCMalloc

    一. 原理 tcmalloc就是一个内存分配器,管理堆内存,主要影响malloc和free,用于降低频繁分配.释放内存造成的性能损耗,并且有效地控制内存碎片.glibc中的内存分配器是ptmalloc ...

  10. Debian8 安装wordpress博客

    首先要安装 php5-gd 已保证wordpress可以正常安装 下载Wordpress wget http://wordpress.org/latest.tar.gz 解压 tar -xzvf la ...