Sử dụng Dictionary<int, int> đếm tần suất xuất hiện của từng phần tử. Key là giá trị mảng, Value là số lần.
Ví dụ
using System;
using System.Collections.Generic;
namespace Demo
{
public class Program
{
public static void Main(string[] args)
{
int[] arr = { 89, 12, 56, 89 };
var d = new Dictionary();
foreach (var res in arr)
{
if (d.ContainsKey(res))
d[res]++;
else
d[res] = 1;
}
foreach (var val in d)
Console.WriteLine("{0} xuất hiện {1} lần", val.Key, val.Value);
}
}
}
Kết quả
89 xuất hiện 2 lần 12 xuất hiện 1 lần 56 xuất hiện 1 lần
Mở rộng: Dùng LINQ arr.GroupBy(x => x).Where(g => g.Count() > 1) để lấy các giá trị trùng lặp.