拼吾爱程序人生

首页 » .Net编程 » Linq » Is it time to abandon loops?
cobra - 2008-4-9 9:10:00
Posted by Jonathan Allen  From/InfoQ

With the addition of LINQ, extension methods, and improved anonymous delegates, many algorithms no longer need explicit loops. In a post titled "If you are using a loop, you're doing it wrong", Chuck Jazdzewski looks at a possible future for C#.

Chuck Jazdzewski opens with the source of his quote, a college professor teaching APL. APL is a language from the 60's that focused heavily on vector and matrix operations. While loops existed, they were generally not needed. Chuck continues,
It is similar with LINQ, if you are using a loop you are doing it wrong. I find myself doing a lot of prototyping lately and I am forcing myself to use LINQ; not because I don't like it, far from it, I really like LINQ, but using loops is so ingrained into my psyche that I have to stop myself and force myself to think in LINQ. Every time I am tempted to write a loop that involves a collection or an array I ask myself, could I use LINQ instead? Programmers with more of a database background seem to take to LINQ like a duck to water. They think in sets and vectors, I don't, but I am getting there.
While Chuck relies heavily on LINQ expressions and extension methods, he does not eliminate loops entirely. In one case he has to move them into IEnumerable extension method that hides the complexity from the calling function. This is done for his generic function Reduce, which takes a list of items and combines adjacent items that 'match'. Both the criteria for matching, and how to actually combine them, are passed in as anonymous functions. This makes it unnecessary for anyone to ever write a similar function.

The goal of the code Chuck shows is to create a function that takes a sequence of ranges, text and a name like "Whitespace" or "Keyword", and apply styles to them. In the end his function is reduced to three query statements:
While most commenter's where positive, not everyone was convinced this is the right way to go. Holger Flick writes,
The headline should be "If you are using a loop, somebody might still be able to read your code without need to analyse it" :)

 您可能对 [Linq] 的这些文章也感兴趣:

Linq to Sql 与NHibernate数据库操作性能比较研究 测试程序源码
优秀Linq网站推荐
LINQ解 爱因斯坦迷题
LINQ综合查询语言开发首先要了解
扩展LINQ to SQL:使用Lambda Expression批量删除数据
LINQ体验(8)——Union All/Intersect/Top/Bottom/Paging/SqlMethods
LINQ体验(15)——LINQ to SQL语句之用户定义函数
LINQ本质(一) 映射
使用linq to xml 快速创建RSS
Linq系列:基础与本质(Part II)
1
查看完整版本: Is it time to abandon loops?
Modify by pin5i DZNT_ExpandPackage 2.1.3237 2007-2008 pin5i.com
  Total Unique Visitors: