Tuesday 12 August 2014

Working with Generic List in C# (Add/Remove/update/Sort/Reverse/count)

List:
An array does not dynamically re-size. A List does. With it, you do not need to manage the size on your own. This type is ideal for linear collections not accessed by keys. Dynamic in size, with many methods, List makes life easier.
List is a generic (constructed) type. You need to use < and > in the List declaration. Lists handle any element type.
Here i will going to show you several operation using list


     public void AddupdateDeleteinList()
            {
                List<int> l = new List<int>();
                l.Add(1);
                l.Add(2);
                l.Add(3);
                l.Add(4);
                l.Add(5);
                l.Add(6);
                l.Add(7);
                l.Add(8);
                l.Add(9);
                l.Add(10);
                //the list at begining
                Console.WriteLine("Fresh list at begining");
                foreach (var item in l)
                {
                    Console.WriteLine(item);
                }
                //to remove values from the list
                l.Remove(8);
                Console.WriteLine("list value 8 is remove");
                //to insert element  in certain position
                l.Insert(0, 0);
                Console.WriteLine("0 inserted at 0 position");
                //to remove from specified position like index position
                Console.WriteLine("element removed of index number 3");
                l.RemoveAt(3);
                Console.WriteLine("total count of list {0}",l.Count()  );
                //to sort the list
                l.Sort();
                Console.WriteLine("element are sorted");
                foreach (var item in l)
                {
                    Console.WriteLine(item);
                }
                //to get the list in reverse order
                l.Reverse();
                Console.WriteLine("element are reverse");
                foreach (var item in l)
                {
                    Console.WriteLine(item);
                }
                //the list is the clear
                l.Clear();
                Console.WriteLine("the values in list is cleard ");
               

            }

output:


No comments:

Post a Comment