C#
  Home arrow C# arrow Page 3 - Working with C# 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  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
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? 
C#

Working with C# Collections
By: Barzan "Tony" Antal
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 13
    2008-12-16

    Table of Contents:
  • Working with C# Collections
  • Various Collections
  • Tell Me More!
  • Final Thoughts

  • 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


    Working with C# Collections - Tell Me More!


    (Page 3 of 4 )

    All right, on the previous page we promised an example with Stack, but before we arrive there, there’s still one more thing to say. The Stack is also based on the IEnumerable interface; thanks to this, we can simply go through its elements using a de facto standard foreach loop. This is the simplest, but there are alternatives.

    The Stack collection class also contains a healthy amount of useful methods and properties that can save us time. Let’s enumerate a few: Clone() creates a shallow copy of the stack indifferent of whether the data is of reference type of value; the Peek() method returns the element that is located on the top of the stack but it does not get removed (a la taking a peek); ToArray() copies the stack to an array, and so forth.

    using System;

    using System.Collections;

    public class SampleProgram2{

    public static void Main(){

    Stack testStack = new Stack();

    testStack.Push("developer");

    testStack.Push("shed");

    testStack.Push(10);

    testStack.Push(50);

    while (testStack.Count > 0){

    Console.WriteLine("Peeking " + testStack.Peek() + " element");

    testStack.Pop();

    }

    }

    }

    And the output of the above code snippet is the following.

    Peeking 50 element

    Peeking 10 element

    Peeking shed element

    Peeking developer element

    Working with NameValueCollection classes is really straightforward because there is barely any difference from the ones presented until now. Basically, their scheme is typically of name strings, and to each there is linked another value string. This means we can add new elements in the following fashion:

    testNameValueCol.Add("developer", "shed");

    Furthermore, to retrieve data you can use Get(), GetKey(), GetType(), GetValues() and various other methods as well. Don’t hesitate to head over to the official MSDN documentation, because each is explained thoroughly along with examples.

    For instance, in the above example, calling GetKey() on the first index would return developer while Get() on the same very first index would return shed. Nevertheless, you can iterate through the NameValueCollection with foreach if you use the AllKeys (which gets all keys enclosed within).

    Finally, we are going to cover two more collection classes. First I will explain the  queue class, which should definitely be known since it is just as important as the stack. And in the end, we will finish this article with StringDictionary. The main difference with the former is that instead of objects, the type of data must be string. But in their very basic form, they are hash tables that are limited to strongly typed strings (both the key and its value).

    Declaring queues is just as easy as stacks. We do it by creating a new Queue. Adding new objects can be done using the Enqueue() method. The easiest analogy to help you imagine queues is to picture standing in line at a hypermarket. It is based on the FIFO—‘First in, First Out’ concept. The person that arrived earlier gets out the fastest. Simple!

    Once again, Queue sports a constructor that accepts ICollection implementers outright as arguments just as stacks did. This means we can create queues out of ArrayLists, BiteArrays, and so forth -- basically all kinds of collections that are based on the ICollection interface. The Peek() method can be used to retrieve items from the queue. Don’t forget that the “first” item can always be retrieved (FIFO, remember!).

    The Dequeue() method removes the first item from the queue. The Clear() method simply clears all of its elements, just as it works on all of the collections. Moreover, you can also use the foreach loop to iterate through a queue’s elements. Just be careful when you use cast because the items aren’t returned as you’d expect.

    As promised, let’s also see how to work with StringDictionary collection classes. By now you shouldn’t have any problems with declaring a new collection class, so we’ll skip that part. Moving on, you can also use the Add() method here that takes any string argument. Keep in mind, a StringDictionary collection is a hash table that accepts only strings as keys and its values.

    Iterating through its elements can be done with foreach. But in order to retrieve data you can use properties such as the Keys and Values (they each return collections). The Count property always holds the total number of key/value pairs contained within. The ContainKey() and ContainsValue() in-built functions can be used to determine whether a key or value can be found inside the collection. Both of them return a Boolean.

    More C# Articles
    More By Barzan "Tony" Antal


       · Thank you for reading this article. In this publication I've shown you how to work...
     

    C# ARTICLES

    - Coding a CRC-Generating Algorithm in C
    - Cyclic Redundancy Check
    - Handling Methods and Functions
    - Destroying Objects in C#
    - Creating Objects in C-Sharp
    - Classes and Objects
    - Programming Languages: Managed versus Native
    - LINQ-to-MySQL with DbLinq in C#
    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek