ASP.NET
  Home arrow ASP.NET arrow Page 2 - Basic Collections
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Moblin 
JMSL Numerical Library 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
ASP.NET

Basic Collections
By: Peyton McCullough
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 4
    2007-11-13

    Table of Contents:
  • Basic Collections
  • Lists Continued
  • Queues
  • Stacks
  • Dictionaries
  • Conclusion

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Basic Collections - Lists Continued


    (Page 2 of 6 )

    All sorts of problems could be caused by mixing types. What happens when one type is expected but another is retrieved? Running this code will raise a System.InvalidCastException since we've added an int to the arrayList:


    foreach (string element in arrayList1)

    {

    Console.WriteLine(element);

    }


    Yes, we could fix this by checking each individual element to see if it is indeed a string, but this is quite messy:


    foreach (object element in arrayList1)

    {

    string elementString = element as string;

    if (elementString != null)

    {

    Console.WriteLine(elementString);

    }

    }


    It's also important to remember that checking for the proper type is not free, especially in large collections. Surely, there must be a better, type-safe way! There is, in the form of generic collections. Generic collections are located in the namespace System.Collections.Generic. A generic list called List is available, and it works just like ArrayList except that only objects of a specific type can be put into it. Here, we create a List with string elements:


    List<string> genericList1 = new List<string>() { "nine", "ten" };


    Now, we know for sure that each element is a string. Attempting to add an object of any other type will raise an exception. Let's enumerate all of the elements:


    foreach (string element in genericList1)

    {

    Console.WriteLine(element);

    }


    To determine how many elements are in a List, the Count property can be read. Here, we write the number of elements in genericList1 to the console:


    Console.WriteLine(genericList1.Count);


    Sometimes, it may be necessary to add an element into the middle of a List. Add only puts a given object at the end of the list. To create a new element anywhere within the list, use the Insert method. Here, we insert a new element into the second position:


    genericList1.Insert(1, "nine and a half");


    All elements to the right (that is, those with a greater index) are bumped up.


    Removing an element from a List is quite simple. In order to remove an element at a given index, the RemoveAt method is used:


    genericList1.RemoveAt(1);


    It's also possible to remove a given object from the List by calling the Remove method. Note, however, that this only removes the first occurrence of the object:


    genericList1.Remove("nine");


    We can also remove all elements from a List using the Clear method:


    genericList1.Clear();


    Sorting in a List is very simple as well with the Sort method. Let's create a List called names that contains several names. Then, we'll sort them alphabetically:


    List<string> names = new List<string>() { "David", "Adam", "Charles", "Jason" };


    names.Sort();


    We can also reverse the order of the elements in a List by calling the Reverse method:


    names.Reverse();


    Searching through a list can also be done through instance methods. To determine if a List contains a given object, the Contains method is used, which returns a boolean value indicating whether or not the object is in the list:


    bool danielFound = names.Contains("Daniel");


    If we need the index of an element, the IndexOf method can be used. It returns the index of the first occurrence of a given object. If the object is not found, it returns -1:


    int jasonsLocation = names.IndexOf("Jason");

    int chucksLocation = names.IndexOf("Chuck");


    List also defines a BinarySearch method, which searches for a given object using a binary search algorithm. This, however, requires that the List to be searched is sorted. The method returns the index of the object, if found, or a negative number:


    names.Sort();

    int adamsLocation = names.BinarySearch("Adam");

    int nicksLocation = names.BinarySearch("Nick");


    No, a List isn't an array, of course, but you are able to copy the elements of a List to an array using the ToArray method:


    string[] nameArray = names.ToArray();

    More ASP.NET Articles
    More By Peyton McCullough


       · Hello,This is an introduction to basic collections, with an emphasis on generic...
     

    ASP.NET ARTICLES

    - Retrieving Data with AJAX and the GridView C...
    - Playing with Images in ASP.NET 3.5 AJAX Appl...
    - Saving and Retrieving Data with AJAX
    - Enhancing PHP Via the ASP.NET AJAX Framework...
    - Enhancing PHP Programming with the ASP.NET A...
    - Classes and ASP.NET AJAX
    - Using ASP.NET AJAX
    - Building a Simple Storefront with LINQ
    - Developing a Dice Game Using ASP.NET Futures...
    - Completing an ASP.NET AJAX Server-Centric Ba...
    - Information Management for an ASP.NET AJAX S...
    - Comment and Order Management for an ASP.NET ...
    - Back-end Management Tasks for an ASP.NET AJA...
    - User Information Management for an ASP.NET A...
    - Adding Comments and Search to an ASP.NET AJA...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway