循环结构根植于几乎所有高级语言的设计中,但对于某些语言如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)
}
显然查询语句方法更加简洁和直观。
本文比较了C#中使用传统循环结构生成(x,y)对并按距离排序与利用LINQ查询语法的简洁方法。查询语句不仅代码量更少,而且更直观地表达意图。
&spm=1001.2101.3001.5002&articleId=134548673&d=1&t=3&u=9effbeac0f494daebf8eec6c836a4925)
876

被折叠的 条评论
为什么被折叠?



