Insert() मेथड से लिस्ट में आइटम इंसर्ट करना
पहले से बनी लिस्ट में आइटम इंसर्ट करने के लिए Insert() मेथड का उपयोग करें।
एलिमेंट्स सेट करें:
List<int> list = new List<int>(); list.Add(989); list.Add(345); list.Add(654); list.Add(876); list.Add(234); list.Add(909);
4th पोज़ीशन (इंडेक्स 3) पर इंसर्ट करें:
// 4th पोज़ीशन पर एलिमेंट इंसर्ट करना (इंडेक्स 3) list.Insert(3, 567);
पूर्ण कोड उदाहरण
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(989); list.Add(345); list.Add(654);
list.Add(876); list.Add(234); list.Add(909);
Console.WriteLine("Count: {0}", list.Count);
Console.Write("List: ");
foreach (int i in list) Console.Write(i + " ");
// 4th पोज़ीशन पर इंसर्ट (इंडेक्स 3)
list.Insert(3, 567);
Console.Write("\nList after inserting a new element: ");
foreach (int i in list) Console.Write(i + " ");
Console.WriteLine("\nCount: {0}", list.Count);
}
}
}
आउटपुट (अपेक्षित):
Count: 6 List: 989 345 654 876 234 909 List after inserting a new element: 989 345 654 567 876 234 909 Count: 7
महत्वपूर्ण बिंदु:
Insert(index, item)- इंडेक्स 0-बेस्ड है- इंडेक्स पर मौजूद एलिमेंट और बाद के एलिमेंट्स दाएँ शिफ्ट होते हैं
- इंडेक्स
Countके बराबर हो सकता है (अंत में जोड़ने के लिए,Addके समान) - इंडेक्स < 0 या > Count पर
ArgumentOutOfRangeExceptionफेंकता है