Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
SumOfEvens
//Rextester.Program.Main is the entry point for your code. Don't change it. //Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Rextester { public class Program { public static void Main(string[] args) { Random r = new Random (1001); int n = r.Next(1000); int[] lotsOfInts = new int[n]; for (int i=0;i<n;i++) lotsOfInts[i] = r.Next(1000); int s1 = SumOfEvensLinq (lotsOfInts), s2 = SumOfEvensIteration (lotsOfInts), s3 = SumOfEvensPFor (lotsOfInts), s4 = SumOfEvensPLinq (lotsOfInts); Console.WriteLine(s1 == s2); Console.WriteLine(s2 == s3); Console.WriteLine(s3 == s4); } // this does filtering first, probably worst static int SumOfEvensLinq(int[] lotsOfInts) { // return the sum of all of the even numbers in lotsOfInts // don’t worry about the possibility of the sum // overflowing an int return lotsOfInts.Where(i => i%2==0).Sum(); } static int SumOfEvensPLinq(int[] lotsOfInts) { int sum = 0; Parallel.ForEach(lotsOfInts, x=> { if (x % 2 == 0) sum += x; }); return sum; } static int SumOfEvensIteration(int[] lotsOfInts) { int sum=0; for (int i=0; i<lotsOfInts.Length; i++) if (lotsOfInts[i] % 2 == 0) sum += lotsOfInts[i]; return sum; } static int SumOfEvensPFor(int[] lotsOfInts) { int sum=0; Parallel.For (0,lotsOfInts.Length, i=> { if (lotsOfInts[i] % 2 == 0) sum += lotsOfInts[i]; }); return sum; } } }
run
|
edit
|
history
|
help
0
GEFCSADX
Multi-Dimensional Array
c# string abbreviation
Hello
bubbleSort
Basic event
asxasdxsd
Binary Search Tree
Trabbd
List, Object, Classes, Function