Linq基本语法概述
创始人
2024-06-06 22:10:15
0

在向大家详细介绍Linq基本语法之前,首先让大家了解下调用Enumberalbe扩展函数,然后全面介绍Linq基本语法。

Linq基本语法

  1. var result = from item in container orderby value ascending/descending select item; 

1、获取全部记录

  1. var allCars = from c in myCars select c; 

2、只获取字段名称

  1. var names = from c in myCars select c.PetName; 

这里names就是隐式类型的变量。

3、使用Enumerable.Distinct()

  1. var makes = (from c in myCars select c.Make).Distinct(); 

4、即可以在定义的时候调用Enumberalbe扩展函数

  1. var names = from c in myCars select c.PetName;  
  2. foreach (var n in names)  
  3. {  
  4. Console.WriteLine("Name: {0}", n);  

也可以在兼容的数组类型上调用

  1. var makes = from c in myCars select c.Make;  
  2. Console.WriteLine("Distinct makes:");  
  3. foreach (var m in makes.Distinct())  
  4. {  
  5. Console.WriteLine("Make: {0}", m);  

 

  1. // Now get only the BMWs.  
  2. var onlyBMWs = from c in myCars where c.Make == "BMW" select c; 

 

  1. // Get BMWs going at least 100 mph.  
  2. var onlyFastBMWs = from c in myCars  
  3. where c.Make == "BMW" && c.Speed >= 100  
  4. select c; 

5、生成新的数据类型(投影)

  1. var makesColors = from c in myCars select new {c.Make, c.Color}; 

6、Reverse()

或者

  1. var subset = (from c in myCars select c).Reverse();  
  2. foreach (Car c in subset)  
  3. {  
  4. Console.WriteLine("{0} is going {1} MPH", c.PetName, c.Speed);  

7、排序

默认是ascending

  1. // Order all the cars by PetName.  
  2. var subset = from c in myCars orderby c.PetName select c;  
  3. // Now find the cars that are going less than 55 mph,  
  4. // and order by descending PetName  
  5. subset = from c in myCars  
  6. where c.Speed > 55 orderby c.PetName descending select c; 

默认顺序时也可以明确指明

  1. var subset = from c in myCars  
  2. orderby c.PetName ascending select c; 

8、Enumerable.Except()
两个IEnumerable兼容的对象的差集

  1. static void GetDiff()  
  2. {  
  3. List myCars = new List 
  4. { "Yugo", "Aztec", "BMW"};  
  5. List yourCars = new List 
  6. { "BMW", "Saab", "Aztec" };  
  7. var carDiff =(from c in myCars select c)  
  8. .Except(from c2 in yourCars select c2);  
  9. Console.WriteLine("Here is what you don't have, but I do:");  
  10. foreach (string s in carDiff)  
  11. Console.WriteLine(s); // Prints Yugo.  

以上介绍Linq基本语法

【编辑推荐】

  1. Linq to SQL学习经验
  2. Linq隐式类型化局部变量
  3. Linq匿名类型简单概述
  4. Linq Lambda表达式剖析
  5. Linq对象初始值浅谈

相关内容

热门资讯

如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...
《非诚勿扰》红人闫凤娇被曝厕所... 【51CTO.com 综合消息360安全专家提醒说,“闫凤娇”、“非诚勿扰”已经被黑客盯上成为了“木...
2012年第四季度互联网状况报... [[71653]]  北京时间4月25日消息,据国外媒体报道,全球知名的云平台公司Akamai Te...