Sunday, September 19, 2010

Working with Generics


Working with Generics:
Most of the classes of System.Collection hold the element as object type. Generics are more specialized collections classes which are used to group the specified type of elements. Generics are type-safe container classes that can only operate on a particular type of data. System.Collections.Generics namespace is introduced in the .net 2.0 version. Most commonly used collections classes are ArrayList and Hashtable and their equivalent Generic types are List and Dictionary.
Working with List:
List<string> Products = new List<string>();
ADD():
Is used to add elements to the generic collection.
List<string> Products = new List<string>();
            Products.Add("FM Transmitter");
            Products.Add("DJ Cable");
            Products.Add("Adapter");
AddRange():
Is used to add a specified range of elements to array.
  List<string> Products = new List<string>();

            string[] products = { "FM Transmitter ", "DJ Cable ", " Adapter " };
            Products.AddRange(products);
BinarySearch():
Is used to search entire collection.
Products.BinarySearch("FM Transmitter ") returns index value as 0.
Contains():
Is used to determine whether an element is in the Collection.
Products.Contains("DJ Cable").
CopyTo():

copies entire list to the specified array, starting at the beginning of the target array.
string[ ] products = {“FM Transmitter ", "DJ Cable ", “Adapter " };
Products.AddRange(products);           
string[ ] b = new string[3];
Products.CopyTo(b);
GetRange():
GetRange method is used to extract the range of elements or to create a new collection of elements from an existing list.
string[,] c = new string[2,2] { {"hello","hi"},{"hello","hi"} };
Products.Add(c);       
foreach (string [,]f in list.GetRange(0, 1))
        {
                Console.WriteLine("{0}.{1}",f[0,0],f[0,1]);
         }
Indexof():

Is used to find the index of an element in the List.
Products.IndexOf(" Adapter"); returns the zero based index value as 2.

Insert():
Is used to add an element at a specified index.
List<string> Products = new List<string>();
Products.Insert(0,"HeadPhone");
InsertRange():
Is used to add a specified range of items to list at a specified index:
string[ ] products = {“FM Transmitter ", "DJ Cable ", “Adapter " };
Products.AddRange(products);           
Products.InsertRange (0, products);
Remove:
Is used to remove an item from the list depending on the given string value.
List<string> Products = new List<string>();
            Products.Add("FM Transmitter");
            Products.Add("DJ Cable");
            Products.Add("Adapter");s
Products.Remove("Adapter");
RemoveAt:
Is used to remove an element from the list at a specified index:
List<string> Products = new List<string>();
Products.Add("FM Transmitter");
Products.Add("DJ Cable");
Products.Add("Adapter");
Products.RemoveAt(0)
Sort() and Reverse():
Is used to sort and reverse the Products.
List<string> Products = new List<string>();
Products.Add("FM Transmitter");
Products.Add("DJ Cable");
Products.Add("Adapter");
Products.Sort();
Products.Reverse();
Using List to maintain product objects:
For example consider u have an products class as follows,  u can work with it by using List class as follows:
public class products
    {
        private string id, name, price;
        // constructor
        public  products()
        {

        }
        public products(string _id, string _name, string _price)
        {
            id = _id;
            name = _name;
            price = _price;
        }
        public string ID
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
            }
        }
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
        public string Price
        {
            get
            {
                return price;
            }
            set
            {
                price = value;
            }
        }
    }

Using List AddRange Method():
List<products> prdts = new List<products>();
            prdts.AddRange(new products[] { new products("FMT", "FM Transmitter", "$43"), new products("DJC", "DJ Cable", "$54") });
Using List Add Method():
List<products> prdts = new List<products>();
            prdts.Add(new products("FMT", "FM Transmitter", "$43"));
            prdts.Add(new products("DJC", "DJ Cable", "$54"));
Iterating through the object in the collection:
foreach (products p in prdts)
            {
                Console.WriteLine("{0}{1}{2}", p.ID,p.Name,p.Price);
            }
Working with Dicitionary:

Dicitionary class is one of the effective collection classes available in the Sytsem.Collections namespace. Out of all available classes ArrayList and Dicitionary are used more frequently. Apart from all the collection classes Dicitionary has got one additional feature, i.e., it allows to store the element with a unique key value. Dicitionary allows to store the elements as key value pairs. Dicitionary organize the element based on the hash code of the key.

Common Methods used in Dicitionary:
Add():
Is used to add elements to the Dicitionary, with a unique key as follows. We can assign the productid with collections of products.
Insert elements into  Dicitionary:
Dictionary<string, string> Products = new Dictionary<string, string>();
            Products.Add("FT", "FM Transmitter");
            Products.Add("DC", "DJCable");
            Products.Add("Ad", "Power Adapter");
Remove():
Is used to remove the element with specified key from the Dictionary.
Dictionary<string, string> Products = new Dictionary<string, string>();
            Products.Add("FT", "FM Transmitter");
            Products.Add("DC", "DJCable");
            Products.Add("Ad", "Power Adapter");
            Console.WriteLine("Before the element is removed");
            foreach (DictionaryEntry s in Products)
            {
                Console.WriteLine("Product ID:{0}\t Product Name:{1}", s.Key, s.Value);
            }
            Products.Remove("Ad");
            Console.WriteLine("====================");
            Console.WriteLine("After the element is removed");
            foreach (DictionaryEntry s in Products)
            {
                Console.WriteLine("Product ID:{0}\t Product Name:{1}", s.Key, s.Value);
            }
Contains() and Containskey():
Returns a boolean value which is used to determine whether the dicitionary contains the specified key.
Dictionary<string, string> Products = new Dictionary<string, string>();
Products.Add("FT", "FM Transmitter");
Products.Add("DC", "DJCable");
Products.Add("Ad", "Power Adapter");
Console.WriteLine("{0}", Products.Contains<string>("Ad"));            Console.WriteLine("{0}", Products.ContainsKey("Ad"));

ContainsValue():
Returns a boolean value which is used to determine whether the dictionary contains the specified value.
Dictionary<string, string> Products = new Dictionary<string, string>();
Products.Add("FT", "FM Transmitter");
Products.Add("DC", "DJCable");
Products.Add("Ad", "Power Adapter");
Console.WriteLine("{0}", Products.ContainsValue("DJCable"));

CopyTo():
Is used to copies entire elements in the dictionary to an existing one dimensional array.
string[ ] products = new string[ 3 ];
Dictionary<string, string> Products = new Dictionary<string, string>();
Products.Add("FT", "FM Transmitter");
Products.Add("DC", "DJCable");
Products.Add("Ad", "Power Adapter");
Products.CopyTo(products, 0);
foreach (string s in products)
    {
       Console.WriteLine("{0}", s);
    }

Next:
Working with types in  System.IO.

Furhter Reading:

No comments:

Post a Comment