74 lines
2.1 KiB
C#
74 lines
2.1 KiB
C#
using System.Diagnostics;
|
|
|
|
class Program {
|
|
static void Main() {
|
|
while (true) {
|
|
Console.WriteLine();
|
|
Console.WriteLine("=== Prestanda-LINQ/Loop-meny ===");
|
|
Console.WriteLine("1: Summa med LINQ");
|
|
Console.WriteLine("2: Summa med loop");
|
|
Console.WriteLine("0: Avsluta");
|
|
Console.Write("Ditt val: ");
|
|
|
|
var choice = Console.ReadLine();
|
|
if (choice == "0") {
|
|
Console.WriteLine("Avslutar...");
|
|
break;
|
|
}
|
|
|
|
int n = ReadPositiveInt("Hur många tal vill du generera? ");
|
|
|
|
var data = CreateRandomList(n, maxValue: n);
|
|
|
|
var sw = Stopwatch.StartNew();
|
|
long result = 0;
|
|
|
|
switch (choice) {
|
|
case "1":
|
|
result = SumWithLinq(data);
|
|
break;
|
|
case "2":
|
|
result = SumWithLoop(data);
|
|
break;
|
|
default:
|
|
Console.WriteLine("Ogiltigt val. Försök igen.");
|
|
continue;
|
|
}
|
|
|
|
sw.Stop();
|
|
|
|
Console.WriteLine($"Resultat: {result}");
|
|
Console.WriteLine($"Tid: {sw.ElapsedMilliseconds} ms för n = {n}");
|
|
}
|
|
}
|
|
|
|
static int ReadPositiveInt(string prompt) {
|
|
while (true) {
|
|
Console.Write(prompt);
|
|
if (int.TryParse(Console.ReadLine(), out int n) && n > 0)
|
|
return n;
|
|
Console.WriteLine("Ange ett heltal större än 0.");
|
|
}
|
|
}
|
|
|
|
static List<long> CreateRandomList(int n, int maxValue) {
|
|
var rnd = new Random();
|
|
var list = new List<long>(n);
|
|
for (int i = 0; i < n; i++)
|
|
list.Add(rnd.Next(-maxValue, maxValue));
|
|
return list;
|
|
}
|
|
|
|
static long SumWithLinq(IEnumerable<long> numbers) {
|
|
return numbers.Where(n => n > 0).Sum(n => (long)n * 2);
|
|
}
|
|
|
|
static long SumWithLoop(IEnumerable<long> numbers) {
|
|
long sum = 0;
|
|
foreach (var n in numbers) {
|
|
if (n > 0) sum += (long)n * 2;
|
|
}
|
|
|
|
return sum;
|
|
}
|
|
} |