Tuesday, May 15, 2007

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.

}

Share:

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews