Sunday, 13 May 2012

Collections in C# 4.0

In C# Collections are in-built data structures,to store & Retrieve structural information. It is classified into generic & non-generics.
In non-generic all types will return as object class, need to type cast it to appropriate type. So non-generic collections are weakly typed.

in Generics appropriate type will be given at compile time, all objects return same type not object type, so it is strongly typed.

Non-Generic Collections included in  System.Collections Namespace
Generics included in System.Collections.Generic.

Generic Collections

  1. List<T>
  2. Stack<T> & Queue<T>
  3. Dictionary<TKey,TValue>
  4. HashSet<T>
  5. LinkedList<T>

1.List<T>

public class Stocks
{
  public string Symbol{get;set;}
  public decimal price{get;set;}
 public DateTime dt{get;set;}
}

Create list of Stock objects.

List<Stocks> stockList = new List<Stocks>();


Insert Items into List

            stockList.Add(new Stocks{ dt=System.DateTime.Now,Symbol="CSCO", price=22.23M});
            stockList.Add(new Stocks { dt = System.DateTime.Now, Symbol = "MSFT", price = 28.99M });
            stockList.Add(new Stocks { dt = System.DateTime.Now, Symbol = "IBM", price = 88.90M });
            stockList.Add(new Stocks { dt = System.DateTime.Now, Symbol = "FB", price = 22.23M });
            stockList.Add(new Stocks { dt = System.DateTime.Now, Symbol = "GooG", price = 580.97M });

Capacity of List class stockList: Initial is 4, there after it will be incremented by 4.
so stockList capacity is  8.

Trim stockList capacity to 5 i.e trim to number of elements in the List by calling
stockList.TrimExcess();  //output would be 5 otherwise 8.

List to Array Conversion
  Stocks[]stocksinArray=stockList.ToArray();

Access List Elements by Index

            try
            {
                for(int i=0; i < stockList.Count;i++)
                {
                Stocks firstElement = stockList[i];
                Console.WriteLine("Symbol={0},price={1},date={2}", firstElement.Symbol, firstElement.price, firstElement.dt);
                }
            }
            catch (IndexOutOfRangeException ex)
            {
                Console.WriteLine(ex.Message);
            }


Find Stock based on Field.i.e Symbol
            bool exists=stockList.Exists(s => s.Symbol == "IBM");
            Console.WriteLine("is IBM Stock  exists={0}",exists);

No comments:

Post a Comment