Để kiểm tra và đếm số lần xuất hiện của các phần tử trong mảng, dùng Dictionary<TKey, TValue> hoặc LINQ GroupBy.
Cách 1: Dùng Dictionary (hiệu năng tốt)
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int[] arr = { 87, 55, 23, 87, 45, 23, 98 };
var counts = new Dictionary();
foreach (int num in arr)
{
if (counts.ContainsKey(num))
counts[num]++;
else
counts[num] = 1;
}
Console.WriteLine("Số lần xuất hiện:");
foreach (var kvp in counts)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value} lần");
}
// Kiểm tra có trùng lặp không
bool hasDuplicates = counts.Any(kvp => kvp.Value > 1);
Console.WriteLine($"\nCó phần tử trùng: {hasDuplicates}");
}
}
Cách 2: Dùng LINQ GroupBy (ngắn gọn)
using System.Linq;
var duplicates = arr
.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(g => new { Value = g.Key, Count = g.Count() });
foreach (var d in duplicates)
Console.WriteLine($"{d.Value} xuất hiện {d.Count} lần");
Kết quả đầu ra
Số lần xuất hiện: 87: 2 lần 55: 1 lần 23: 2 lần 45: 1 lần 98: 1 lần Có phần tử trùng: True
Phức tạp: O(n) thời gian, O(n) bộ nhớ. Dictionary nhanh hơn GroupBy cho mảng lớn.