我可以使用无限的范围,并在它运作? [英] Can I use infinite range and operate over it?

查看:159
本文介绍了我可以使用无限的范围,并在它运作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Enumerable.Range(0, int.MaxValue)
          .Select(n => Math.Pow(n, 2))
          .Where(squared => squared % 2 != 0)
          .TakeWhile(squared => squared < 10000).Sum()

将这段代码遍历所有从0到最大范围,或只是通过整数值的整数值的满足起飞时,其中,选择运营商?
能有人澄清

Will this code iterate over all of the integer values from 0 to max-range or just through the integer values to satisfy the take-while, where, and select operators? Can somebody clarify?

编辑:我的第一次尝试,以确保它能正常工作是愚蠢的。我撤销:)

My first try to make sure it works as expected was dumb one. I revoke it :)

推荐答案

int.MaxValue + 5 溢出到是一个负数。自己尝试一下:

int.MaxValue + 5 overflows to be a negative number. Try it yourself:

unchecked
{
    int count = int.MaxValue + 5;
    Console.WriteLine(count); // Prints -2147483644
}



对于第二个参数可枚举.Range 必须为非负 - 因此例外

The second argument for Enumerable.Range has to be non-negative - hence the exception.

可以肯定是在LINQ使用无穷序列虽然。下面是这样一个顺序的例子:

You can certainly use infinite sequences in LINQ though. Here's an example of such a sequence:

public IEnumerable<int> InfiniteCounter()
{
    int counter = 0;
    while (true)
    {
        unchecked
        {
            yield return counter;
            counter++;
        }
    }
}

这会溢出为好,当然,但它会继续下去...

That will overflow as well, of course, but it'll keep going...

注意部分的LINQ运算符(如反向)需要阅读的所有的数据才可以得到自己的第一个结果。其他(如选择)可以只保留流结果,因为它们从输入读取。看到我的 Edulinq博客文章的每个操作行为的详细信息(在LINQ to对象)。

Note that some LINQ operators (e.g. Reverse) need to read all the data before they can yield their first result. Others (like Select) can just keep streaming results as they read them from the input. See my Edulinq blog posts for details of the behaviour of each operator (in LINQ to Objects).

这篇关于我可以使用无限的范围,并在它运作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆