WindowsDevCenter.com
oreilly.comSafari Books Online.Conferences.

advertisement


AddThis Social Bookmark Button

C# Generics: Collection Interfaces
Pages: 1, 2, 3, 4, 5, 6, 7

List<T>

The classic problem with the Array type is its fixed size. If you don't know in advance how many objects an array will hold, you run the risk of declaring either too small an array (and running out of room) or too large an array (and wasting memory).



Your program might be asking the user for input, or gathering input from a web site. As it finds objects (strings, books, values, etc.), you will add them to the array, but you have no idea how many objects you'll collect in any given session. The classic fixed-size array is not a good choice, as you can't predict how large an array you'll need.

The List class is an array whose size is dynamically increased as required. Lists provide a number of useful methods and properties for their manipulation. Some of the most important are shown in Table 9-3.

Table 9-3. List methods and properties

Method or property

Purpose

Capacity

Property to get or set the number of elements the List can contain. This value is increased automatically if count exceeds capacity. You might set this value to reduce the number of reallocations, and you may call Trim() to reduce this value to the actual Count.

Count

Property to get the number of elements currently in the array.

Item( )

Gets or sets the element at the specified index. This is the indexer for the List class. [4]

Add( )

Public method to add an object to the List.

AddRange( )

Public method that adds the elements of an ICollection to the end of the List.

BinarySearch( )

Overloaded public method that uses a binary search to locate a specific element in a sorted List.

Clear( )

Removes all elements from the List.

Contains( )

Determines if an element is in the List.

CopyTo( )

Overloaded public method that copies a List to a one-dimensional array.

Exists( )

Determines if an element is in the List.

Find( )

Returns the first occurrence of the element in the List.

FindAll( )

Returns all the specified elements in the List.

GetEnumerator( )

Overloaded public method that returns an enumerator to iterate through a List.

GetRange( )

Copies a range of elements to a new List.

IndexOf( )

Overloaded public method that returns the index of the first occurrence of a value.

Insert( )

Inserts an element into the List.

InsertRange( )

Inserts the elements of a collection into the List.

LastIndexOf( )

Overloaded public method that returns the index of the last occurrence of a value in the List.

Remove( )

Removes the first occurrence of a specific object.

RemoveAt( )

Removes the element at the specified index.

RemoveRange( )

Removes a range of elements.

Reverse( )

Reverses the order of elements in the List.

Sort( )

Sorts the List.

ToArray( )

Copies the elements of the List to a new array.

TrimToSize( )

Sets the capacity of the actual number of elements in the List.

When you create a List, you don't define how many objects it will contain. Add to the List using the Add() method, and the list takes care of its own internal bookkeeping, as illustrated in Example 9-13.

Example 9-13. Working with List
#region Using directives

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

#endregion

namespace ListCollection
{
   // a simple class to store in the List
   public class Employee
   {
      private int empID;

      public Employee( int empID )
      {
         this.empID = empID;
      }
      public override string ToString( )
      {
         return empID.ToString( );
      }
      public int EmpID
      {
         get
         {
            return empID;
         }
         set
         {
            empID = value;
         }
      }
   }
   public class Tester
   {
      static void Main( )
      {

         List<Employee> empList = new List<Employee>( );
         List<int> intList = new List<int>( );

         // populate the List
         for ( int i = 0; i < 5; i++ )
         {
            empList.Add( new Employee( i + 100 ) );
            intList.Add( i * 5 );
         }

         // print all the contents
         for ( int i = 0; i < intList.Count; i++ )
         {
            Console.Write( "{0} ", intList[i].ToString( ) );
         }

         Console.WriteLine( "\n" );

         // print all the contents of the Employee List
         for ( int i = 0; i < empList.Count; i++ )
         {
            Console.Write( "{0} ", empList[i].ToString( ) );
         }

         Console.WriteLine( "\n" );
         Console.WriteLine( "empList.Capacity: {0}",
            empList.Capacity );
      }
   }
}

Output:
0 5 10 15 20
100 101 102 103 104
empArray.Capacity: 16

With an Array class, you define how many objects the array will hold. If you try to add more than that, the Array class will throw an exception. With a List, you don't declare how many objects the List will hold. The List has a property, Capacity, which is the number of elements the List is capable of storing:

public int Capacity { get; set; }

The default capacity is 16. When you add the 17th element, the capacity is automatically doubled to 32. If you change the for loop to:

for (int i = 0;i<17;i++)

the output looks like this:

0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
empArray.Capacity: 32

You can manually set the capacity to any number equal to or greater than the count. If you set it to a number less than the count, the program will throw an exception of type ArgumentOutOfRangeException.

Pages: 1, 2, 3, 4, 5, 6, 7

Next Pagearrow