代码改变世界

Effective C# 学习笔记(八)多用query语法,少用循环

2011-07-03 22:55  小郝(Kaibo Hao)  阅读(843)  评论(0编辑  收藏  举报

对于C#query查询语法,其可读性和可维护性要比原来的loop操作好得多

例子:

同样是创建个二维元组,并对其元组按到原点的距离进行倒序排序,用query 语法的表达形式要比原始的循环做法来的更易读、更易于维护,并且省去了用于存储中间过程的额外临时变量(例子中原始方法用的 storage对象)

 

//原始的循环方法

private static IEnumerable<Tuple<int, int>> ProduceIndices3()

{

var storage = new List<Tuple<int, int>>();

for (int x = 0; x < 100; x++)

for (int y = 0; y < 100; y++)

if (x + y < 100)

storage.Add(Tuple.Create(x, y));

storage.Sort((point1, point2) =>

(point2.Item1*point2.Item1 +

point2.Item2 * point2.Item2).CompareTo(

point1.Item1 * point1.Item1 +

point1.Item2 * point1.Item2));

return storage;

}

 

//query syntax

private static IEnumerable<Tuple<int, int>> QueryIndices3()

{

  return from x in Enumerable.Range(0, 100)

    from y in Enumerable.Range(0, 100)

    where x + y < 100

    orderby (x*x + y*y) descending

    select Tuple.Create(x, y);

}

 

 

//using the method call syntax

private static IEnumerable<Tuple<int, int>> MethodIndices3()

{

return Enumerable.Range(0, 100).

SelectMany(x => Enumerable.Range(0,100),

(x,y) => Tuple.Create(x,y)).

Where(pt => pt.Item1 + pt.Item2 < 100).

OrderByDescending(pt =>

pt.Item1* pt.Item1 + pt.Item2 * pt.Item2);

}