Linq的基本语法概述

发布时间:2021-09-01 14:45:32 作者:chen
来源:亿速云 阅读:90

这篇文章主要介绍“Linq的基本语法概述”,在日常操作中,相信很多人在Linq的基本语法概述问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Linq的基本语法概述”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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

Linq基本语法

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

1、获取全部记录

var allCars = from c in myCars select c;

2、只获取字段名称

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

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

3、使用Enumerable.Distinct<T>()

var makes = (from c in myCars select c.Make).Distinct<string>();

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

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

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

var makes = from c in myCars select c.Make;  Console.WriteLine("Distinct makes:");  foreach (var m in makes.Distinct<string>())  {  Console.WriteLine("Make: {0}", m);  }
// Now get only the BMWs.  var onlyBMWs = from c in myCars where c.Make == "BMW" select c;
// Get BMWs going at least 100 mph.  var onlyFastBMWs = from c in myCars  where c.Make == "BMW" && c.Speed >= 100  select c;

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

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

6、Reverse<T>()

或者

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

7、排序

默认是ascending

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

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

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

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

static void GetDiff()  {  List<string> myCars = new List<String> { "Yugo", "Aztec", "BMW"};  List<string> yourCars = new List<String> { "BMW", "Saab", "Aztec" };  var carDiff =(from c in myCars select c)  .Except(from c2 in yourCars select c2);  Console.WriteLine("Here is what you don't have, but I do:");  foreach (string s in carDiff)  Console.WriteLine(s); // Prints Yugo.  }

到此,关于“Linq的基本语法概述”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. mongodb的基本语法
  2. javascript基本语法

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

linq

上一篇:javascript中push()方法有什么用

下一篇:Vue全局自定义指令Modal拖拽的示例分析

相关阅读

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

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