Insert() मेथड से इंडेक्स पर आइटम जोड़ना
लिस्ट सेट करें:
List<int> list = new List<int>(); list.Add(456); list.Add(321); list.Add(123); list.Add(877); list.Add(588); list.Add(459);
इंडेक्स 5 पर आइटम जोड़ें:
list.Insert(5, 999);
पूर्ण कोड उदाहरण
using System;
using System.Collections.Generic;
namespace Demo {
public class Program {
public static void Main(string[] args) {
List<int> list = new List<int>();
list.Add(456); list.Add(321); list.Add(123);
list.Add(877); list.Add(588); list.Add(459);
Console.Write("List: ");
foreach (int i in list) Console.Write(i + " ");
Console.WriteLine("\nCount: {0}", list.Count);
// इंडेक्स 5 पर इंसर्ट
list.Insert(5, 999);
Console.Write("\nList after inserting a new element: ");
foreach (int i in list) Console.Write(i + " ");
Console.WriteLine("\nCount: {0}", list.Count);
}
}
}
आउटपुट (अपेक्षित):
List: 456 321 123 877 588 459 Count: 6 List after inserting a new element: 456 321 123 877 588 999 459 Count: 7
Insert vs Add:
| मेथड | व्यवहार |
|---|---|
| Add(item) | अंत में जोड़ता है (O(1) अमॉर्टाइज़्ड) |
| Insert(index, item) | निर्दिष्ट इंडेक्स पर जोड़ता है, बाद के एलिमेंट्स शिफ्ट (O(n)) |
इंडेक्स मान्यता:
- मान्य रेंज:
0सेCountतक index == Countअंत में जोड़ने के बराबर (Addजैसा)- अमान्य इंडेक्स पर
ArgumentOutOfRangeException