Linq使用Select浅谈
创始人
2024-06-06 18:20:37
0

在向大家详细介绍Linq使用Select之前,首先让大家了解下Linq To Sql查询数据库,然后全面介绍Linq使用Select。

下面通过一些例子来说明怎样Linq使用Select,参考自:LINQ Samples

1.  可以对查询出来的结果做一些转换,下面的例子在数组中查找以"B"开头的名字,然后全部转成小写输出:

  1. string[] names = { "Jack", "Bob", "Bill", "Catty", "Willam" };  
  2. var rs = from n in names  
  3. where n.StartsWith("B")  
  4. select n.ToLower();  
  5. foreach (var r in rs)  
  6. Console.WriteLine(r); 

2. 返回匿名类型,比如Linq To Sql查询数据库的时候只返回需要的信息,下面的例子是在Northwind数据库中查询Customer表,返回所有名字以"B"开头的客户的ID和名称:

  1. NorthwindDataContext dc = new NorthwindDataContext();  
  2. var cs = from c in dc.Customers  
  3. where c.ContactName.StartsWith("B")  
  4. select new  
  5. {  
  6. CustomerID = c.CustomerID,  
  7. CustomerName = c.ContactTitle + " " + c.ContactName  
  8. };  
  9. foreach (var c in cs)  
  10. Console.WriteLine(c); 

3. 对于数组,select可以对数组元素以及索引进行操作:

  1. string[] names = { "Jack", "Bob", "Bill", "Catty", "Willam" };  
  2. var rs = names.Select((name, index) => new { Name = nameIndex = index });  
  3. foreach (var r in rs)  
  4. Console.WriteLine(r);  

4. 组合查询,可以对多个数据源进行组合条件查询(相当于Linq使用SelectMany函数),下面的例子其实就相对于一个双重循环遍历:

  1. int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };  
  2. int[] numbersB = { 1, 3, 5, 7, 8 };  
  3.  
  4. var pairs =  
  5. from a in numbersA,  
  6. b in numbersB  
  7. where a < b 
  8. select new {a, b};  
  9.  
  10. Console.WriteLine("Pairs where a < b:");  
  11. foreach (var pair in pairs)  
  12. Console.WriteLine("{0} is less than {1}", pair.a, pair.b); 

而用Linq To Sql的话,相当于进行一次子查询:

  1. NorthwindDataContext dc = new NorthwindDataContext();  
  2. var rs = from c in dc.Customers  
  3. from o in c.Orders  
  4. where o.ShipCity.StartsWith("B")  
  5. select new { CustomerName = c.ContactName, OrderID = o.OrderID };  
  6.  
  7. foreach (var r in rs)  
  8. Console.WriteLine(r); 

【编辑推荐】

  1. LINQ to SQL Table浅谈
  2. Linq语句问题的解决方法
  3. Ling to sql更新实体概述
  4. Linq实体继承简单描述
  5. Linq Library概述

相关内容

热门资讯

如何允许远程连接到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...