นับจำนวนครั้งที่เลข 1 ปรากฏในอาร์เรย์
ตัวอย่างโค้ดเต็ม
using System;
public class Demo {
public static void Main() {
int count = 0;
int[] num = new int[] {1, 25, 1, 55, 1};
Console.WriteLine("Numbers:");
for (int i = 0; i < 5; i++) {
Console.WriteLine(num[i]);
}
foreach (int j in num) {
if (j == 1) {
count++;
}
}
Console.WriteLine("Number of 1's: ");
Console.WriteLine(count);
Console.ReadLine();
}
}
ผลลัพธ์
Numbers: 1 25 1 55 1 Number of 1's: 3
วิธีทางเลือก (LINQ):
int count = num.Count(x => x == 1); // ต้อง using System.Linq;