কম্পিউটার টিউটোরিয়াল

LINQ C#-তে Select এবং SelectMany-এর পার্থক্য

মূল পার্থক্য

বিষয়SelectSelectMany
ক্যাটেগরিProjection OperatorProjection 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 একই কাজ করে
  1. DirectX 11 এবং DirectX 12-এর পার্থক্য কী?

  2. C#-এ লিটারেল (Literal) এবং কনস্ট্যান্ট (Constant) এর পার্থক্য

  3. C#-এ String (ক্লাস) এবং string (এলিয়াস) এর পার্থক্য

  4. C#-এ লিস্ট এবং অ্যারেতে পার্থক্য (List vs Array)