In distinct elements: Distinct() LINQ hoặc Dictionary đếm tần suất = 1.
Ví dụ minh họa
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int[] arr = { 88, 23, 56, 96, 43 };
Console.WriteLine("Mảng: " + string.Join(", ", arr));
// Cách 1: LINQ Distinct (tất cả phần tử unique)
var distinct = arr.Distinct();
Console.WriteLine("\nDistinct (tất cả):");
foreach (int x in distinct) Console.WriteLine($"{x} xuất hiện 1 lần");
// Cách 2: Dictionary - lọc tần suất = 1
var counts = new Dictionary();
foreach (int x in arr)
counts[x] = counts.GetValueOrDefault(x) + 1;
Console.WriteLine("\nDictionary (tần suất = 1):");
foreach (var kvp in counts.Where(k => k.Value == 1).OrderBy(k => k.Key))
Console.WriteLine($"{kvp.Key} xuất hiện {kvp.Value} lần");
// Test với mảng có duplicate
int[] arr2 = { 1, 2, 2, 3, 4, 4, 5 };
Console.WriteLine($"\nMảng có duplicate: {string.Join(", ", arr2)}");
Console.WriteLine("Phần tử chỉ xuất hiện 1 lần:");
foreach (int x in arr2.GroupBy(v => v).Where(g => g.Count() == 1).Select(g => g.Key))
Console.WriteLine(x);
}
}
Kết quả đầu ra
Mảng: 88, 23, 56, 96, 43 Distinct (tất cả): 88 xuất hiện 1 lần 23 xuất hiện 1 lần 56 xuất hiện 1 lần 96 xuất hiện 1 lần 43 xuất hiện 1 lần Dictionary (tần suất = 1): 23 xuất hiện 1 lần 43 xuất hiện 1 lần 56 xuất hiện 1 lần 88 xuất hiện 1 lần 96 xuất hiện 1 lần Mảng có duplicate: 1, 2, 2, 3, 4, 4, 5 Phần tử chỉ xuất hiện 1 lần: 1 3 5
Phân biệt: "Distinct elements" = loại bỏ duplicate (giữ 1). "Elements appearing once" = tần suất = 1 (loại bỏ hoàn toàn các phần tử trùng).