মূল পার্থক্য
| বিষয় | Select | SelectMany |
|---|---|---|
| ক্যাটেগরি | Projection Operator | Projection Operator (Flattening) |
| ফলাফল | প্রতিটি সোর্স এলিমেন্টের জন্য একটি রেজাল্ট (কালেকশন অফ কলেকশন) | সব সিকোয়েন্স ফ্ল্যাটেন করে একক সিকোয়েন্সে |
| রিটার্ন টাইপ | IEnumerable<IEnumerable<T>> | IEnumerable<T> |
| ব্যবহার | এক-से-এক ম্যাপিং | এক-से-অনেক, নেস্টেড কালেকশন ফ্ল্যাটেন |
উদাহরণ
using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
public string Name { get; set; }
public List<string> Contents { get; set; }
public static List<Demo> GetAllContents() {
return new List<Demo> {
new Demo { Name = "Cap", Contents = new List<string> { "Nike", "Adidas" } },
new Demo { Name = "Shoes", Contents = new List<string> { "Nike", "Puma", "Adidas" } }
};
}
}
class Program {
static void Main() {
// SELECT - নেস্টেড লিস্ট রিটার্ন করে
IEnumerable<List<string>> resultSelect = Demo.GetAllContents()
.Select(s => s.Contents);
Console.WriteLine("--- Select ---");
foreach (List<string> stringList in resultSelect) {
foreach (string str in stringList) {
Console.WriteLine(str);
}
}
// SELECTMANY - ফ্ল্যাটেন করে একক সিকোয়েন্স
IEnumerable<string> resultSelectMany = Demo.GetAllContents()
.SelectMany(s => s.Contents);
Console.WriteLine("\n--- SelectMany ---");
foreach (string str in resultSelectMany) {
Console.WriteLine(str);
}
Console.ReadKey();
}
}
আউটপুট:
--- Select --- Nike Adidas Nike Puma Adidas --- SelectMany --- Nike Adidas Nike Puma Adidas
লক্ষ্য করুন: আউটপুট একই見える, কিন্তু Select-এ নেস্টেড লুপ দরকার, SelectMany-এ একই লুপে সব পাওয়া যায়।
SelectMany-এর আরও উদাহরণ
১. ক্রস জয়েন (Cartesian Product)
var numbers = new[] { 1, 2 };
var letters = new[] { "A", "B" };
var pairs = numbers.SelectMany(n => letters, (n, l) => $"{n}{l}");
// Result: 1A, 1B, 2A, 2B
২. নেস্টেড অবজেক্ট থেকে ফ্ল্যাট লিস্ট
var departments = new[] {
new { Name = "IT", Employees = new[] { "Alice", "Bob" } },
new { Name = "HR", Employees = new[] { "Carol" } }
};
var allEmployees = departments.SelectMany(d => d.Employees);
// Result: Alice, Bob, Carol
৩. Where + SelectMany কম্বিনেশন
var expensiveProducts = orders
.Where(o => o.Total > 1000)
.SelectMany(o => o.Items)
.Select(i => i.ProductName);
স্মরণ রাখার পয়েন্ট
Select= ম্যাপ (Map) — এক ইনপুট → এক আউটপুটSelectMany= বাইন্ড (Bind/FlatMap) — এক ইনপুট → শূন্য/এক/অনেক আউটপুট, তারপর ফ্ল্যাটেন- যদি সোর্স এলিমেন্টই স্ক্যালার (নন-কলেকশন) হয়, তবে
SelectManyওSelectএকই কাজ করে