Linq如何使用Select

发布时间:2021-11-03 14:02:19 作者:小新
来源:亿速云 阅读:114

这篇文章给大家分享的是有关Linq如何使用Select的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

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

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

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. 组合查询,可以对多个数据源进行组合条件查询(相当于Linq使用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”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. LINQ TO SQL中的select和selectMany区别
  2. LINQ查询如何使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

linq select

上一篇:Linq如何使用sqlmetal

下一篇:Linq如何使用Group By

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》