推迟查询的执行
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceConsoleApplication3{classProgram{staticvoidMain(string[]args){//迭代在查询定义的时候不会进行,而是在执行每个foreach语句时执行//每次迭代中使用查询时,都会调用扩展方法List<string>strs=newList<string>{"关羽","张飞","马超","黄忠","赵云"};varquery=fromrinstrswherer.StartsWith("张")//查找集合中元素匹配第一个的元素orderbyrselectr;Foreach(query);//输出:张飞strs.Add("张昭");strs.Add("张合");strs.Add("张辽");strs.Add("曹操");Foreach(query);//输出:张飞,张合,张辽,张昭Console.ReadKey();//==========================================两次输出不变(值添加到集合里面去了)List<string>strs2=newList<string>{"关羽","张飞","马超","黄忠","赵云"};varquery2=(fromrinstrs2wherer.StartsWith("张")//查找集合中元素匹配第一个的元素orderbyrselectr).ToList();//ToArray()ToEnumerable()Foreach(query2);//输出:张飞strs2.Add("张昭");strs2.Add("张合");strs2.Add("张辽");strs2.Add("曹操");Foreach(query2);//输出:张飞Console.ReadKey();}staticvoidForeach(IEnumerable<string>s){foreach(stringitemins){Console.WriteLine(item);}Console.WriteLine("=========================");}}}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。