简体   繁体   English

LINQ为什么不能按预期工作?

[英]Why doesn't LINQ work as expected?

I have created a simple program to calculate primes as follows: 我创建了一个简单的程序来计算素数,如下所示:

        var db = new HighScoreEntities();
        List<Int64> primes = new List<Int64>(){1};
        for (Int64 x = 2; x < Int64.MaxValue; x++)
        {
            if (primes.FirstOrDefault(y=> x%y == 0) == 0){
                primes.Add(x);
                db.Primes.AddObject(Prime.CreatePrime(x));
                db.SaveChanges();
            }
        }

My issue is that y is coming out with 225 on the first go through and what seems like random numbers afterwards. 我的问题是, y第一次通过225,之后看起来像随机数。 Why isn't it iterating through the 'primes' list? 为什么不遍历“素数”列表? I also tried using the Exists function with the same result. 我也尝试使用Exists函数获得相同的结果。

1 isn't a prime, so adding it to primes is probably a bad start. 1不是素数,因此将其添加到primes可能是一个不好的开始。 It looks like on every loop iteration you are finding the first element in primes such that the remainder of x / 1 is 0, which will always be true. 看起来在每次循环迭代中,您都发现primes的第一个元素,使得x / 1的余数为0,这将始终为真。

I didn't try the program out myself so I could be wrong, but that should be a good place to start. 我没有亲自尝试该程序,因此可能会出错,但这应该是一个不错的起点。

I think you want the .Any operator 我认为您想要.Any运算符

if (!primes.Any(y=> x%y == 0) )

Also there are many examples of using LINQ and PLINQ for calculating primes. 也有许多使用LINQ和PLINQ计算素数的示例。 Here's just one. 这只是一个。

First issue I see with this code is that primes list is initialized with 1. There are two problems with that number - 1 is not prime number, and 1 will always meet requirements presented in FirstOrDefault lambda, because any number modulo one will give 0 in result. 我用此代码看到的第一个问题是质primes列表是用1初始化的。该数字有两个问题-1不是质数,并且1将始终满足FirstOrDefault lambda中提出的要求,因为任何模数为1的模数都为0结果。

Apart from that, everything seems to be rather ok. 除此之外,一切似乎还不错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM