December 2007
Intermediate to advanced
896 pages
19h 57m
English
You want to be able to access elements contained in your nongeneric collection type using the foreach statement.
Implement IEnumerable on your nongeneric type:
public class StampCollection : IEnumerable
{
private Dictionary<string, Stamp> _stamps =
new Dictionary<string, Stamp>();
public void Add(Stamp stamp)
{
_stamps.Add(stamp.Name, stamp);
}
public IEnumerator GetEnumerator()
{
// Return all stamps in the stamp collection
// in order of publication
var orderedStamps = from Stamp stamp in _stamps.Values
orderby stamp.Year
select stamp;
foreach (Stamp stamp in orderedStamps)
{
yield return stamp;
}
}
}
public class Stamp
{
public Stamp(int year, string name)
{
this.Year = year;
this.Name = name;
}
public int Year { get; set; }
public string Name { get; set; }
public override string ToString()
{
return this.Year + ":" + this.Name;
}
}The following code creates a new StampCollection and fills it with Stamps; it then proceeds to use a foreach loop to enumerate and display each Stamp:
public static void TestStampCollection()
{
//Create a StampCollection and fill it with stamps
StampCollection stamps = new StampCollection() {
new Stamp(1998,"Louisiana Duck"),
new Stamp(1968,"Goethals Memorial"),
new Stamp(1909,"Carmine Hudson"),
new Stamp(1936,"Hotel Corner Card")};
foreach (Stamp stamp in stamps)
{
Console.WriteLine(stamp);
}
}When adding an iterator to a nongeneric type, the IEnumerable interface needs to be implemented. ...
Read now
Unlock full access