দুটি অ্যারে বা লিস্টে কমন এলিমেন্ট খুঁজে বের করতে HashSet<T> এবং IntersectWith বা LINQ Intersect ব্যবহার করা হয়।
HashSet IntersectWith পদ্ধতি (দ্রুত)
var set1 = new HashSet<int>(arr1);
var set2 = new HashSet<int>(arr2);
set1.IntersectWith(set2); // set1 এখন কমন এলিমেন্ট ধারণ করে
LINQ Intersect পদ্ধতি (সহজ)
var common = arr1.Intersect(arr2);
সম্পূর্ণ উদাহরণ (দুই পদ্ধতিই)
using System;
using System.Collections.Generic;
using System.Linq;
class CommonElementsDemo
{
public static void Main()
{
int[] arr1 = { 65, 57, 63, 98 };
int[] arr2 = { 43, 65, 33, 57 };
// পদ্ধতি ১: HashSet
var h1 = new HashSet<int>(arr1);
var h2 = new HashSet<int>(arr2);
h1.IntersectWith(h2);
Console.WriteLine("HashSet পদ্ধতিতে কমন: " + string.Join(", ", h1));
// পদ্ধতি ২: LINQ
var common = arr1.Intersect(arr2);
Console.WriteLine("LINQ পদ্ধতিতে কমন: " + string.Join(", ", common));
}
}
আউটপুট
HashSet পদ্ধতিতে কমন: 65, 57
LINQ পদ্ধতিতে কমন: 65, 57
তুলনা
HashSet.IntersectWithইন-প্লেস কাজ করে, মেমরি দক্ষ।Enumerable.Intersectলেজি, রিড-অনলি, চেইনেবল।- দুইটিই O(n+m) জটিলতা।