C# list

C# provides a List class that you can store many values of the same type. When you use List class you are safe from type casting because it allows to specify the type of values to be stored in the list when its object is created.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Csharp
{

   class Program
   {
    

     static void Main(string[] args)
     {
        //create List object to store integer values
        List<int> lst = new List<int>();
        lst.Capacity = 100; //Set possible number of items can be stored in the list
        //Add items to the list
        for (int i = 0; i < 10; i++)
           lst.Add(i * i);
        //insert items to the list
        lst.Insert(1, 100);
        lst.Insert(3, 100);
        lst.Sort(); //sort the list in ascending order
              
        //Read all items in the list a long with their indices
        int index = 0;
        foreach (int item in lst)
        {
           Console.Write("{0}\t{1}\n",item,index);
           index++;
        }
      
      
        //check to see whether 100 exists in the list
         if (lst.Contains(100)) Console.WriteLine("\nExists...");
      
        //Remove an item from the list by value
        lst.Remove(0); //remove 0 from the list
        //Remove an item from the list by index
        lst.RemoveAt(1);//remove the item at index 1
        //remove all items from the list
        lst.Clear();
        
       Console.Read();

     }
  }
}

Posted by: Dara | post date: 01-28-2013 | Subject: C# Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.