Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีแทรกข้อมูลใน List ตำแหน่งที่กำหนดใน C#

ใช้เมธอด Insert() เพื่อแทรกข้อมูลใน List ที่มีอยู่แล้ว

ขั้นแรก เพิ่มข้อมูล:

List<int> list = new List<int>();
list.Add(989);
list.Add(345);
list.Add(654);
list.Add(876);
list.Add(234);
list.Add(909);

แทรกข้อมูลที่ตำแหน่งที่ 4 (ดัชนี 3):

// inserting element at 4th position
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 + " "); }
            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);
        }
    }
}