循环结构根植于几乎所有高级语言的设计中,但对于某些语言如C#来说,有一个更好用的替代方法:linq查询语法(或方法语法)。
假设我们需要一个从0到99的(x, y)对,其需要满足条件:其返回的数组必须按照它们到原点的距离递减排列。
循环imperative语句方法:
private static IEnumerable<Tuple<int, int>> QueryIndices()
{
List<Tuple<int, int>> indices = new List<Tuple<int, int>>();
// 生成从 0 到 99 的 (x, y) 对
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
indices.Add(Tuple.Create(x, y));
}
}
// 按照到原点的距离递减排列
indices = indices.OrderByDescending(t => DistanceToOrigin(t.Item1, t.Item2)).ToList();
return indices;
}
private static double DistanceToOrigin(int x, int y)
{
// 计算到原点的距离
return Math.Sqrt(x * x + y * y);
}
}
查询语句方法:
private static IEnumerable<Tuple<int, int>> QueryIndices()
{
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)
}
显然查询语句方法更加简洁和直观。