Generics C#

Insert Elements into a List

This C# program demonstrates how to insert elements into a list.

Program.cs

using System;
using System.Collections.Generic;


namespace XoaX {

    class Program {
        static void Main(string[] args) {
            // An array of the names of new testament books
            string[] saNewTestamentBooks = new string[]{
                "Matthew", "Mark", "Luke", "John",
                "Acts", "Romans"
            };

            List<string> qBooksNT = new List<string>(saNewTestamentBooks);

            // Display the initial list
            Console.WriteLine("First Books List:");
            Console.WriteLine("-----------------");
            foreach (string sBook in qBooksNT) {
                Console.WriteLine(sBook);
            }
            Console.WriteLine("");

            string[] saMore = new string[]{
                "Ephesians", "Philippians", "Colossians"
            };

            // Create a second list
            List<string> qMoreBooks = new List<string>(saMore);

            // Display the second list
            Console.WriteLine("More Books List:");
            Console.WriteLine("----------------");
            foreach (string sBook in qMoreBooks) {
                Console.WriteLine(sBook);
            }
            Console.WriteLine("");

            // Insert the second into the first
            qBooksNT.InsertRange(4, qMoreBooks);

            // Display the inserted list
            Console.WriteLine("After Insert Range:");
            Console.WriteLine("-------------------");
            foreach (string sBook in qBooksNT) {
                Console.WriteLine(sBook);
            }
            Console.WriteLine("");

            // Insert Titus at eighth element
            qBooksNT.Insert(7, "Titus");

            // Display the second inserted list
            Console.WriteLine("After Insert Titus:");
            Console.WriteLine("-------------------");
            foreach (string sBook in qBooksNT) {
                Console.WriteLine(sBook);
            }
            Console.WriteLine("");
        }
    }
}
 

Output

First Books List:
-----------------
Matthew
Mark
Luke
John
Acts
Romans

More Books List:
----------------
Ephesians
Philippians
Colossians

After Insert Range:
-------------------
Matthew
Mark
Luke
John
Ephesians
Philippians
Colossians
Acts
Romans

After Insert Titus:
-------------------
Matthew
Mark
Luke
John
Ephesians
Philippians
Colossians
Titus
Acts
Romans

Press any key to continue . . .
 
 

© 2007–2025 XoaX.net LLC. All rights reserved.