如何在 C# 中某個給定位置插入一個項到列表?
要在已建立的列表中插入一項,請使用 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);
現在,假設你需要在第 4 個位置插入一項。為此,請使用 Insert() 方法 -
// 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 + " ");
}
// inserting element at 4th position
list.Insert(3, 567);
Console.Write("
List after inserting a new element: ");
foreach(int i in list) {
Console.Write(i + " ");
}
Console.WriteLine("
Count: {0}", list.Count);
}
}
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP