Monday, January 23, 2012

How to Use foreach in Multiple classes

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

namespace Indexer
{

public class NameDetail
{
public string FirstName { get; set; }
public string MiddleName{ get; set; }
public string LastName { get; set; }
public string FullName
{
get
{
String strFullname="";
if (string.IsNullOrEmpty(FirstName) == false )
{
strFullname = FirstName;
}
if (string.IsNullOrEmpty(MiddleName) == false)
{
strFullname += MiddleName;
}
if (string.IsNullOrEmpty(LastName) == false)
{
strFullname += LastName;
}
return strFullname.Trim();
}

}
}

public class Name: IDisposable, IEnumerable, IEnumerator
{
List arrPos = new List();
public int count { get ;set ;}
private int Position = -1; // This is for Ienum interface

public NameDetail this[int pos]
{
get
{
try
{
return arrPos[pos];
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
set
{
if (arrPos.Count <= pos)
{
arrPos.Insert(pos, value);
count = arrPos.Count;
}
else
{
throw new Exception("No Index postiion");
}
}
}
#region IDisposable
public void Dispose()
{
arrPos = null;
}
#endregion IDisposable


//**********************************************************
//********************* Use For Each in object *************
//*********************************************************
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return (IEnumerator)this;
}
public bool MoveNext()
{
if (Position < arrPos.Count - 1)
{
++Position;
return true;
}
return false;
}
public void Reset()
{
Position =-1;
}
public object Current
{
get
{
return arrPos[Position];
}
}
#endregion
}



class Program
{
static void Main(string[] args)
{
Name a = new Name();
NameDetail ND ;
ND = new NameDetail();
ND.FirstName = "Mohit";
ND.LastName = "Agrawal";
a[0] = ND;
ND = new NameDetail();
ND.FirstName = "aaa";
a[1] = ND;

foreach (NameDetail n in a)
{
Console.WriteLine(n.FirstName );
Console.WriteLine(n.MiddleName);
Console.WriteLine(n.LastName );
Console.WriteLine(n.FullName);
}
Console.ReadKey();
a.Dispose();
a = null;
ND = null;
}
}
}

No comments:

Post a Comment

Hash Table in C#

 The Hashtable is a non-generic collection and used to store the key/value pairs based on the hash code of the key. Key will be used to acce...