Linq 扩展函数的应用

问题描述

xxx.Where((aa,bb)=>aa.Length<bb);明白以上代码是什么意思?(大家都是谈初学,高手浏览即可)1、Where子句其实是用扩展方法来实现的MS实现的Where子句对应的扩展函数是如下的定义:namespaceSystem.Linq{publicdelegateTResultFunc<TArg0,TArg1,TResult>(TArg0arg0,TArg1arg1);publicstaticclassEnumerable{publicstaticIEnumerable<TSource>Where<TSource>(thisIEnumerable<TSource>source,Func<TSource,bool>predicate);publicstaticIEnumerable<TSource>Where<TSource>(thisIEnumerable<TSource>source,Func<TSource,int,bool>predicate);}}其中红色字体的那个扩展函数,就是我们上面代码实际使用的扩展函数。我们这个扩展函数参数:Func<TSource,int,bool>predicate的定义看上面代码的绿色delegate代码。2、Where子句参数书写的是Lambda表达式((aa,bb)=>aa.Length<bb);就相当于C#2.0的匿名函数。LINQ中所有关键字比如Select,SelectMany,Count,All等等其实都是用扩展方法来实现的。上面的用法同样也适用于这些关键字子句。3、这个Where子句中Lambda表达式第二个参数是数组索引,我们可以在Lambda表达式内部使用数组索引。来做一些复杂的判断。具有数组索引的LINQ关键字除了Where还以下几个Select,SelectMany,Count,All我们下面就来依次举例Select子句使用数组索引的例子下面代码有一个整数数组,我们找出这个数字是否跟他在这个数组的位置一样publicstaticvoidLinqDemo01(){int[]numbers={5,4,1,3,9,8,6,7,2,0};varnumsInPlace=numbers.Select((num,index)=>new{Num=num,InPlace=(num==index)});Console.WriteLine("Number:In-place?");foreach(varninnumsInPlace)Console.WriteLine("{0}:{1}",n.Num,n.InPlace);}输出结果:Number:In-place?5:False4:False1:False3:True9:False8:False6:True7:True2:False0:False其中我们用到的这个Select子句对应的扩展函数定义,以及其中Func<TSource,int,TResult>委托定义如下:publicstaticIEnumerable<TResult>Select<TSource,TResult>(thisIEnumerable<TSource>source,Func<TSource,int,TResult>selector);publicdelegateTResultFunc<TArg0,TArg1,TResult>(TArg0arg0,TArg1arg1);SelectMany子句使用数组索引的例子几个句子组成的数组,我们希望把这几个句子拆分成单词,并显示每个单词在那个句子中。查询语句如下:publicstaticvoidDemo01(){string[]text={"Albertwashere","Burkesleptlate","Connorishappy"};vartt=text.SelectMany((s,index)=>fromssins.Split('')selectnew{Word=ss,Index=index});foreach(varnintt)Console.WriteLine("{0}:{1}",n.Word,n.Index);}结果:Albert:0was:0here:0Burke:1slept:1late:1Connor:2is:2happy:2SkipWhile子句使用数组索引的例子SkipWhile意思是一直跳过数据,一直到满足表达式的项时,才开始返回数据,而不管之后的项是否仍然满足表达式,需要注意他跟Where是不一样的,Where是满足条件的记录才返回,SkipWhile是找到一个满足条件的,然后后面的数据全部返回。下面例子返回一个整数数组中,这个整数比他自身在这个数组的位置大于等于的第一个位置以及之后的数据。publicstaticvoidLinq27(){int[]numbers={5,4,1,3,9,8,6,7,2,0};varlaterNumbers=numbers.SkipWhile((n,index)=>n>=index);Console.WriteLine("Allelementsstartingfromfirstelementlessthanitsposition:");foreach(varninlaterNumbers)Console.WriteLine(n);}输出结果:Allelementsstartingfromfirstelementlessthanitsposition:13986720First、FirstOrDefault、Any、All、Count子句注意:101LINQSamples中First-Indexed、FirstOrDefault-Indexed、Any-Indexed、All-Indexed、Count-Indexed这五个例子在OrcasBeta1中已经不在可用,即下面代码是错误的。publicvoidLinq60(){int[]numbers={5,4,1,3,9,8,6,7,2,0};intevenNum=numbers.First((num,index)=>(num%2==0)&&(index%2==0));Console.WriteLine("{0}isanevennumberatanevenpositionwithinthelist.",evenNum);}publicvoidLinq63(){double?[]doubles={1.7,2.3,4.1,1.9,2.9};double?num=doubles.FirstOrDefault((n,index)=>(n>=index-0.5&&n<=index+0.5));if(num!=null)Console.WriteLine("Thevalue{1}iswithin0.5ofitsindexposition.",num);elseConsole.WriteLine("Thereisnonumberwithin0.5ofitsindexposition.",num);}publicvoidLinq68(){int[]numbers={-9,-4,-8,-3,-5,-2,-1,-6,-7};boolnegativeMatch=numbers.Any((n,index)=>n==-index);Console.WriteLine("Thereisanumberthatisthenegativeofitsindex:{0}",negativeMatch);}publicvoidLinq71(){int[]lowNumbers={1,11,3,19,41,65,19};int[]highNumbers={7,19,42,22,45,79,24};boolallLower=lowNumbers.All((num,index)=>num<highNumbers[index]);Console.WriteLine("Eachnumberinthefirstlistislowerthanitscounterpartinthesecondlist:{0}",allLower);}publicvoidLinq75(){int[]numbers={5,4,1,3,9,8,6,7,2,0};intoddEvenMatches=numbers.Count((n,index)=>n%2==index%2);Console.WriteLine("Thereare{0}numbersinthelistwhoseodd/evenstatus"+"matchesthatoftheirposition.",oddEvenMatches);}要实现这个功能,可以用Where子句,如下:publicstaticvoidLinq60(){int[]numbers={5,4,1,3,9,8,6,7,2,0};intevenNum=numbers.Where((num,index)=>(num%2==0&&index%2==0)).First();Console.WriteLine("{0}isanevennumberatanevenpositionwithinthelist.",evenNum);}publicstaticvoidLinq63(){double?[]doubles={1.7,2.3,4.1,1.9,2.9};double?num=doubles.Where((n,index)=>(n>=index-0.5&&n<=index+0.5)).FirstOrDefault();if(num!=null)Console.WriteLine("Thevalue{1}iswithin0.5ofitsindexposition.",num);elseConsole.WriteLine("Thereisnonumberwithin0.5ofitsindexposition.",num);}publicstaticvoidLinq68(){int[]numbers={-9,-4,-8,-3,-5,-2,-1,-6,-7};boolnegativeMatch=numbers.Where((n,index)=>n==-index).Any();Console.WriteLine("Thereisanumberthatisthenegativeofitsindex:{0}",negativeMatch);}publicstaticvoidLinq71(){int[]lowNumbers={1,11,3,19,41,65,19};int[]highNumbers={7,19,42,22,45,79,24};boolallLower=lowNumbers.Where((num,index)=>num<highNumbers[index]).All(n=>true);Console.WriteLine("Eachnumberinthefirstlistislowerthanitscounterpartinthesecondlist:{0}",allLower);}publicstaticvoidLinq75(){int[]numbers={5,4,1,3,9,8,6,7,2,0};intoddEvenMatches=numbers.Where((n,index)=>n%2==index%2).Count();Console.WriteLine("Thereare{0}numbersinthelistwhoseodd/evenstatus"+"matchesthatoftheirposition.",oddEvenMatches);}转自:http://www.cnblogs.com/RuiLei/archive/2007/07/17/820507.html

解决方案

解决方案二:
学习了
解决方案三:
樓主,不錯
解决方案四:
顶mark
解决方案五:
jf,学习
解决方案六:
mark
解决方案七:
扩展函数的确很好很强大...
解决方案八:
该回复于2008-03-16 10:34:01被版主删除
解决方案九:
扩展函数的确很好很强大...
解决方案十:
jf&&up
解决方案十一:
扩展函数充分发挥Linq功能.感谢楼主分享!
解决方案十二:
引用10楼lt5225262的回复:

扩展函数充分发挥Linq功能.感谢楼主分享!

时间: 2024-07-28 12:33:08

Linq 扩展函数的应用的相关文章

Linq系列:基础与本质(Part I)

之前写过一些C#3.x新的特性.请参考:C#3.x特性,我们知道这些新的特性基本都是为实现LINQ服务的,在平常的编程中也可以有选择的合 理应用,也会有效提高编码效率,实现可读性比较强的简洁代码.在认识这些特性的基础上,理解认识LINQ将变得简单了. 1 LINQ简介: LINQ 查询表达式(query expressions )可以使用统一的方式对实现IEnumberable<T>接口的对象.关系数据库.数据集(Datasets )以及XML文档进行访问. 严格的说,LINQ是用来描述一系列

[转] LINQ的经典例子-Where,Select、SelectMany、SkipWhile子句中使用数组索引。

Where 子句的用法 我们除了可以如下方式书写带Where子句的LINQ外: from p in products where p.UnitsInStock > 0 && p.UnitPrice > 3.00M select p; 还可以对数组(所有实现了IEnumerable接口的对象都可以)的实体使用 Where 扩展方法.   把一个查询语句写成多个扩展函数的方式,这其实是编译器处理查询语句的方法,比如下面的查询语句: int[] arr = new int[] { 8

LINQ 的查询执行何时是延迟执行,何时是立即执行,以及查询的复用

问题描述 延迟执行的经典例子:我们用select++i就可以看到在foreach时候,查询才被执行.publicstaticvoidLinq99(){int[]numbers=newint[]{5,4,1,3,9,8,6,7,2,0};inti=0;varq=fromninnumbersselect++i;foreach(varvinq)Console.WriteLine("v={0},i={1}",v,i);}输出结果:v=1,i=1v=2,i=2v=3,i=3v=4,i=4v=5,

Linq学习教程 Linq to Xml读取复杂xml及Linq to js使用

Linq to Xml读取复杂xml(带命名空间) xml的操作方式有多种,但要论使用频繁程度,博主用得最多的还是Linq to xml的方式,觉得它使用起来很方便,就用那么几个方法就能完成简单xml的读写.之前做的一个项目有一个很变态的需求:C#项目调用不知道是什么语言写的一个WebService,然后添加服务引用总是失败,通过代理的方式动态调用也总是报错,最后没办法,通过发送原始的WebRequest请求直接得到对方返回的一个xml文件.注意过webservice的wsdl文件的朋友应该知道

动态字段名-linq 字段名动态改变 动态添加数据

问题描述 linq 字段名动态改变 动态添加数据 我遇到的问题是: 我要添加的一张表的字段名是动态的,也就是说A网页调用A数据表,B网页调用B数据表.我现在希望写一个基类,来完成这两个表的添加数据操作,而不是采用 表名A.字段名a = 值; 表名A.字段名b = 值; 表名B.字段名c = 值; 表名B.字段名d = 值;的方式进行赋值.我希望的格式为: 表名(是个变量).字段名(是个变量)= 值.谢谢! 解决方案 http://www.cnblogs.com/gmtyt/archive/201

vb.net-VB,net linq 模糊查询List

问题描述 VB,net linq 模糊查询List 我有 一 个书籍列 Dim books As List(Of book) 需要用textbox.text的值 对这个list进行模糊查询,返回list 结果,用循环比较浪费,LINQ 如何做 解决方案 linq 模糊查询linq 模糊查询linq中动态模糊查询

编写自己的php扩展函数

函数 php程序写的时间长了,自然对他所提供的功能了如指掌,他所提供的一大堆功能,真是觉得很好用,但有时候会发现php也缺少一些功能,自己总是会产生为php添加一些自定义的功能的想法.久而久之,终于今天憋不住了,开始动手研究如何添加.     下载一个php的源代码包,这里使用的是php 4.0.5版,解压后会看到php的根目录下会有README.EXT_SKEL这样一个文件,打开详细阅读了一下,发现了一个非常好用的工具,这个工具可以帮你构建一个空的php扩展,然后你向里面添加相应的代码就可以完

wp8-开发WP8.1应用时,引用using Newtonsoft.Json.Linq;,编译出现错误。

问题描述 开发WP8.1应用时,引用using Newtonsoft.Json.Linq;,编译出现错误. 在 System.dll模块中找不到类型System.ComponentModel.PropertyDescriptor. 解决方案 windows phone的.net不支持System.ComponentModel.PropertyDescriptor换别的库解析json 解决方案二: 试试 JavaScriptSerializer:在System.Web.Extensions.dll

Linq之IQueryable接口与IEnumberable区别

IEnumerable接口 公开枚举器,该枚举器支持在指定类型的集合上进行简单迭代.也就是说:实现了此接口的object,就可以直接使用foreach遍历此object:  IEnumerable 包含一个方法,GetEnumerator,返回 IEnumerator. IEnumerator 可以通过集合循环显示 Current 属性和 MoveNext 和 Reset 方法. 它是一个最优方法实现 IEnumerable 和 IEnumerator 在集合选件类启用 foreach (For