by Zoran Horvat
Dec 14, 2014
Suppose that we want to test whether a given integer number greater than one is prime. We can accomplish that with a simple for loop:
int number = 719;
bool isPrime = true;
for (int divisor = 2; divisor <= Math.Sqrt(number); divisor++)
if (number % divisor == 0)
{
isPrime = false;
break;
}
Console.WriteLine("Number {0} is {1}prime.", number, isPrime ? "" : "not ");
This loop works fine and it really detects that 719 is a prime number.
The same effect can be accomplished with LINQ. Here is the LINQ expression which returns exactly the same result as the previous loop:
bool isPrime =
Enumerable.Range(2, (int)Math.Sqrt(number) - 1)
.All(divisor => number % divisor != 0);
This simple expression iterates through numbers up to the square root of the tested value and tries to divide the value with each of the numbers in the range. Loop exits when the first divisor is detected and subsequent divisions are not performed. This guarantees optimal execution of the expression.
If you wish to learn more, please watch my latest video courses
This course begins with examination of a realistic application, which is poorly factored and doesn't incorporate design patterns. It is nearly impossible to maintain and develop this application further, due to its poor structure and design.
As demonstration after demonstration will unfold, we will refactor this entire application, fitting many design patterns into place almost without effort. By the end of the course, you will know how code refactoring and design patterns can operate together, and help each other create great design.
More...
In four and a half hours of this course, you will learn how to control design of classes, design of complex algorithms, and how to recognize and implement data structures.
After completing this course, you will know how to develop a large and complex domain model, which you will be able to maintain and extend further. And, not to forget, the model you develop in this way will be correct and free of bugs.
More...
Zoran Horvat is the Principal Consultant at Coding Helmet, speaker and author of 100+ articles, and independent trainer on .NET technology stack. He can often be found speaking at conferences and user groups, promoting object-oriented development style and clean coding practices and techniques that improve longevity of complex business applications.