Collection<T> इंडेक्सर के माध्यम से शून्य-आधारित इंडेक्स द्वारा तत्वों तक त्वरित पहुंच प्रदान करता है। यह IList<T> लागू करता है और पढ़ने/लिखने का समर्थन करता है।
उदाहरण 1: तत्व पढ़ना
using System;
using System.Collections.ObjectModel;
public class Demo
{
public static void Main()
{
Collection<string> col = new Collection<string>();
col.Add("Laptop");
col.Add("Desktop");
col.Add("Notebook");
col.Add("Ultrabook");
col.Add("Tablet");
col.Add("Headphone");
col.Add("Speaker");
Console.WriteLine("Elements in Collection...");
foreach (string str in col)
{
Console.WriteLine(str);
}
Console.WriteLine("Element at index 3 = " + col[3]);
Console.WriteLine("Element at index 4 = " + col[4]);
}
}
आउटपुट
Elements in Collection... Laptop Desktop Notebook Ultrabook Tablet Headphone Speaker Element at index 3 = Ultrabook Element at index 4 = Tablet
उदाहरण 2: तत्व पढ़ना और अपडेट करना
using System;
using System.Collections.ObjectModel;
public class Demo
{
public static void Main()
{
Collection<string> col = new Collection<string>();
col.Add("Laptop");
col.Add("Desktop");
col.Add("Notebook");
col.Add("Ultrabook");
col.Add("Tablet");
col.Add("Headphone");
col.Add("Speaker");
Console.WriteLine("Elements in Collection...");
foreach (string str in col)
{
Console.WriteLine(str);
}
Console.WriteLine("Element at index 3 = " + col[3]);
col[3] = "SSD";
Console.WriteLine("Element at index 3 (Updated) = " + col[3]);
}
}
आउटपुट
Elements in Collection... Laptop Desktop Notebook Ultrabook Tablet Headphone Speaker Element at index 3 = Ultrabook Element at index 3 (Updated) = SSD
Collection<T> एक आधार वर्ग है जिसका उपयोग कस्टम संग्रह बनाने के लिए किया जाता है। इंडेक्सर O(1) एक्सेस प्रदान करता है। व्युत्पन्न वर्ग InsertItem, SetItem, RemoveItem, ClearItems को ओवरराइड करके व्यवहार को अनुकूलित कर सकते हैं।