LINQ 中的 select
来源:互联网 发布:js 计算合计 编辑:程序博客网 时间:2024/05/13 22:05
下面通过一些例子来说明怎样使用select,
1. 可以对查询出来的结果做一些转换,下面的例子在数组中查找以"B"开头的名字,然后全部转成小写输出:
string[] names = { "Jack", "Bob", "Bill", "Catty", "Willam" }; var rs = from n in names where n.StartsWith("B") select n.ToLower(); foreach (var r in rs) Console.WriteLine(r);
2. 返回匿名类型,比如Linq To Sql查询数据库的时候只返回需要的信息,下面的例子是在Northwind数据库中查询Customer表,返回所有名字以"B"开头的客户的ID和名称:
NorthwindDataContext dc = new NorthwindDataContext(); var cs = from c in dc.Customers where c.ContactName.StartsWith("B") select new { CustomerID = c.CustomerID, CustomerName = c.ContactTitle + " " + c.ContactName }; foreach (var c in cs) Console.WriteLine(c);
3. 对于数组,select可以对数组元素以及索引进行操作:
string[] names = { "Jack", "Bob", "Bill", "Catty", "Willam" }; var rs = names.Select((name, index) => new { Name = name, Index = index }); foreach (var r in rs) Console.WriteLine(r);
4. 组合查询,可以对多个数据源进行组合条件查询(相当于使用SelectMany函数),下面的例子其实就相对于一个双重循环遍历:
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var pairs = from a in numbersA, b in numbersB where a < b select new {a, b}; Console.WriteLine("Pairs where a < b:"); foreach (var pair in pairs) Console.WriteLine("{0} is less than {1}", pair.a, pair.b);
而用Linq To Sql的话,相当于进行一次子查询:
NorthwindDataContext dc = new NorthwindDataContext(); var rs = from c in dc.Customers from o in c.Orders where o.ShipCity.StartsWith("B") select new { CustomerName = c.ContactName, OrderID = o.OrderID }; foreach (var r in rs) Console.WriteLine(r);
- LINQ 中的 select
- LINQ 中的 select
- LINQ 中的 select
- LINQ TO SQL中的select
- LINQ TO SQL--select
- Linq之Select
- LINQ之Select、Distinct
- Linq select 不包含
- linq学习(select)
- Select case in LINQ
- LINQ的Select
- Linq:Select使用示例
- LINQ系列:LINQ to SQL Select查询
- Linq第三天-Select 操作
- linq to sql 用法 ----- select
- linq list select用法注意事项
- LINQ需要select多个值时怎么办?
- C# 中的 LINQ 入门
- tomcat中content.xml中配置连接池的方法
- InputStream读取中文字符并由ByteArrayOutputStream写入
- HTTP协议及其POST与GET操作差异 & C#中如何使用POST、GET等
- C/C++中重复定义的问题
- 如何求sin(angle),其中angle用角度表示。
- LINQ 中的 select
- 实验09《训练功能的流程控制编程》实验指导书V07-2初稿
- 米...
- 用py2exe编译Python程序
- Embed perl in c/c++, C调用perl, perl调用C 技术详解
- Windows Azure AppFabric 入门教学系列 (五):初探Access Control Service
- 认识人的智慧
- 如何检查确认informix数据库空间离线的原因及解决方案
- 从零开始做3D地图编辑器(六)(基于QT与OGRE)