List - Should be used when iteration is based on index.
Syntax: List<Type> lst = new List<Type();
Example:
using System;
using System.Collections.Generic;
namespace TestCollections
{
class Program
{
static void Main(string[] args)
{
List<String> lstEmp = new List<String>();
lstEmp.Add("emp1");
lstEmp.Add("emp2");
lstEmp.Add("emp3");
//Syntax fo Iteration:
foreach (String emp in lstEmp)
{
Console.WriteLine (emp);
}
}
}
}
Dictionary - Should be used when iteration is based on a Key.
- Each object conains a key & Value.
- Key should be unique where as values can repeat.
Example:
using System;
using System.Collections.Generic;
namespace TestCollections
{
class Program
{
static void Main(string[] args)
{
Dictionary<int, string> dictCityNames = new Dictionary<int, string>();
dictCityNames.Add(92127, "San Diego");
dictCityNames.Add(92128, "Los Angels");
dictCityNames.Add(92129, "San Francisco");
//For retreiving Key & Values
foreach (KeyValuePair<int,string> kvp in dictCityNames)
{
Console.WriteLine("Key = {0},Value = {1}", kvp.Key, kvp.Value);
}
//For retreving only keys
foreach(int KeyName in dictCityNames.Keys)
{
Console.WriteLine(KeyName);
}
//For retreving only Values
foreach (string KeyValue in dictCityNames.Values )
{
Console.WriteLine(KeyValue);
}
}
}
}
IEnumerator: Can be used to iterate through a list instead of using "foreach"
Ex:
IEnumerator<string > emp = lstEmp.GetEnumerator();
while (emp.MoveNext())
{
Console.WriteLine(emp.Current);
}
Thanks
Shanti
Sabarimahesh, if this helps please login to Mark As Answer. | Alert Moderator