How to traverse in Collection of ASP.NET,C#.NET

  • Home
  • Blog
  • How to traverse in Collection of ASP.NET,C#.NET

I am creating a 3-tier application using the collections and I have found that it is very difficult to traverse in collection. I have used ICollection and IEnumerator interface to inherit my class.here is the class.

#region Using Directive
using System;
using System.Collections;
using System.Xml;
using System.Xml.Serialization;

#endregion

namespace MyCollectionClass

{
[Serializable]
[XmlRoot(“CountryCollection”)]
public class CountryCollection:IEnumerator,ICollection
{
#region Fields
private int _CountryId;
private string _CountryName;
private ArrayList _CountryList;
private int _Index=-1;

#endregion

#region Properties

public int CountryId
{
get
{
return _CountryId;
}
set
{
_CountryId=value;
}
}
public string CountryName
{
get
{
return _CountryName;
}
set
{
_CountryName=value;
}
}
public object Current
{
get
{
return _CountryList[_Index];
}
}
public Object SyncRoot
{
get
{
return this;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}

public CountryCollection this[int indexer]

{
get
{
if ((indexer >= 0) && (indexer
{
return (CountryCollection)_CountryList[indexer];
}
else
{
throw new System.IndexOutOfRangeException(“Index Must Between 0 and ” + _CountryList.Count.ToString());
}
}
}
int System.Collections.ICollection.Count
{
get
{
return _CountryList.Count;
}
}
public int Count
{
get
{
return _CountryList.Count;
}

}
#endregion

#region Constructor

public CountryCollection()
{
_CountryList = new ArrayList();
}
public CountryCollection(ArrayList theArrayList)
{
_CountryList = theArrayList;
}

#endregion

#region Methods

public void Add(CountryCollection objCountry)
{
_CountryList.Add(objCountry);
}
public void Remove(CountryCollection objCountry)
{
_CountryList.Remove(objCountry);
}
public IEnumerator GetEnumerator()
{
return (IEnumerator)new CountryCollection(_CountryList);
}
public bool MoveNext()
{
_Index++;
return _Index
}
public void Reset()
{
_Index = -1;
}
public ArrayList GetArrayList()
{
return _CountryList;
}
public void CopyTo(Array a, int index)
{
_CountryList.CopyTo(a, index);
}
#endregion
}
}

After that i have create a object of class called objCountryCol.Now here is the way for traversing the data.

Convert objCountryCol into enumerator….

IEnumerator inum=objCountryCol.GetEnumerator();

here is the loop for traversing

while (inum.MoveNext())

{
objCountryCol=(CountryCollection)inum.Current;
///write another code and traverse your class.

}