Add, Retrieve, and Remove items from Generic List

using System; 
using System.Collections.Generic; 
namespace W3ex { 
    class W3ex { 
        static void Main(string[] args) { 
            // create two lists, specifying the initial elements 
            List<string> list1 = new List<string>() { "mom", "dad"}; 
            List<string> list2 = new List<string>() { "uncle", "aunt"}; 
            // use the add range method to add the contents of one list to the other 
            list1.AddRange(list2) ; 
            // enumerate the contents of the list 
            writeList("Combined List", list1) ; 
            // use the GetRange method 
            List<string> rangelist = list1.GetRange(1, 2) ; 
            writeList("GetRange List", rangelist) ; 
            // use the InsertRange method 
            list1.InsertRange(1, rangelist) ; 
            writeList("InsertRange List", list1); 
            // remove a specific item 
            writeList("Removed value aunt", list1); 
            // use RemoveRange 
            list1.RemoveRange(0, 3) ; 
            writeList("RemoveRange List", list1); 
            // wait for input before exiting 
            Console.WriteLine("Press enter to finish"); 
        private static void writeList(string msg, List<string> list) { 
            foreach (string str in list) { 
                Console.WriteLine("List item: {0}", str); 

Enjoyed this post? Share it!


Leave a comment

Your email address will not be published.