Sunday, April 17, 2011

Introduction to List(T) in C#



What is a List<T>?


List<T> is a generic class in the System.Collections.Generic Namespace. An instance of this class is basically a strongly typed arraylist (that is, the type of the items in the collection is fixed at the time of instantiation. )

Consider this example

 ArrayList leaderNames = new ArrayList();
 leaderNames.Add("Obama");
 leaderNames.Add(5);



Notice that this array list consists of a string and an int. That is it is NOT strongly typed.

In the above example if I want to allow just strings to be entered. I will use a strongly typed list as shown below.

List<string> leaderNames = new List<string>(); //Notice here that I am specifying that the List is a List of strings

leaderNames.Add("Obama");
leaderNames.Add("VPutin");



Trying something like this will  throw a compilation error.


leaderNames.Add(7);// will throw error because 7 is not a string


An example that uses List<T>

There are many ready made methods for your use, that comes with with an instance of List<T> class.
The example below shows some things that you can do with an instance of the List<T> class


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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {



            List<string> leaderNames = new List<string>();

            leaderNames.Add("Obama");
            leaderNames.Add("VPutin");

            List<string> womenLeaders = new List<string>();

            womenLeaders.Add("HillaryClinton");
            womenLeaders.Add("SarahPalin");
            leaderNames.AddRange(womenLeaders);//Increase the range of the existing array by adding more items into the List

            foreach (string leader in leaderNames)
            {
                Console.WriteLine(leader);
            }
            /*This is how the output would look like
            Obama
            VPutin
            HillaryClinton
            SarahPalin
            Press any key to continue . . .
              */



            leaderNames.Clear();//Clear all the items

        }
    }
}



How to custom sort the List?


As a continuation of the example above, in this example I have added a class to the solution that inherits the IComparer<T> interface and implements its Compare() method.When you implement this method, all you need to do is write a logic that 

  • throws an output of 1 when the first input item to the Compare() Method is greater
  •  throw an output of -1 when the second input item is greater and
  •  0 when they are equal.



In the example below have written a simple logic in the Compare() method below that compares the input items by their length. 

Add this class file to your solution


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

namespace ConsoleApplication1
{
    class ClassLengthSort : IComparer<string>
    {
        int IComparer<string>.Compare(string x, string y)
        {
            
            if (x.Length > y.Length)
            {
                return 1;
            }
            else if (y.Length > x.Length)
            {
                return -1;
            }
            else
            {
                return 0;
            }
        }
    }
}

Where ever you finish adding items to leaderNames List, just add these two lines of code

  //The next two lines of code sorts the name by their length in an ascending order
  IComparer<string> IC = new ClassLengthSort();
  leaderNames.Sort(IC);





After the sort, your output would look like this (names are sorted in an ascending order of length)



Obama
VPutin
SarahPalin
HillaryClinton


How to find an element in the List?

Check this out for an example on find in list.
http://dotnetanalysis.blogspot.com/2011/12/predicate-c.html


What is the difference between Add and Insert?


Add() adds the item to the bottom of the list. Insert adds the item at the specified index and pushes down the  other items starting at that index. This is demonstrated in the example below



Further Reading
http://dotnetanalysis.blogspot.com/2011/10/introduction-to-generics-c.html

For a complete list of the available properties and methods in the List<T> class go to

0 comments:

Post a Comment