在向大家详细介绍Linq基本语法之前,首先让大家了解下调用Enumberalbe扩展函数,然后全面介绍Linq基本语法。
创新互联公司专业为企业提供河南网站建设、河南做网站、河南网站设计、河南网站制作等企业网站建设、网页设计与制作、河南企业网站模板建站服务,10年河南做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。
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
- var makes = (from c in myCars select c.Make).Distinct
();
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
()) - {
- 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
或者
- var subset = (from c in myCars select c).Reverse
(); - 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
- static void GetDiff()
- {
- List
myCars = new List - { "Yugo", "Aztec", "BMW"};
- List
yourCars = new List - { "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基本语法
分享标题:Linq基本语法概述
文章源于:http://www.shufengxianlan.com/qtweb/news15/26065.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联