Reputation: 283
Here is my class
class EmissionSource:IEnumerable
{
private Emissions[] emissions = new Emissions[5];
private Contribution[] contributions = new Contribution[2];
public EmissionSource()
{
emissions[0] = new Emissions(2010, 400, 200, 6);
emissions[1] = new Emissions(2011, 450, 255, 16);
emissions[2] = new Emissions(2012, 470, 245, 26);
emissions[3] = new Emissions(2013, 490, 285, 36);
emissions[4] = new Emissions(2014, 495, 245, 46);
contributions[0] = new Contribution(1, "Energy");
contributions[1] = new Contribution(3, "Industrial Sector");
}
public IEnumerator GetEnumerator()
{
return emissions.GetEnumerator();
}
}
In the GetEnumerator method, I am delegating the request to the System.Array using emissions object. I was wondering, how can I iterate through other subitem viz contributions like
foreach (Emissions e in source)
{
//
}
foreach (Contribution e in source)
{
//
}
Upvotes: 2
Views: 301
Reputation: 9733
Best I can come up with is just using two different properties:
class Main
{
class X
{
private int[] i = new int[5];
private string[] s = new string[2];
public X()
{
i[0] = 0; i[1] = 1; i[2] = 2; i[3] = 3; i[4] = 4;
s[0] = "test"; s[1] = "test2";
}
public IEnumerable<string> Strings
{
get
{
return s;
}
}
public IEnumerable<int> Ints
{
get
{
return i;
}
}
}
private static void Main(string[] args)
{
X x = new X();
foreach (string s in x.Strings)
{ }
foreach (int i in x.Ints)
{ }
}
}
I've tried using the generic versions of IEnumerable and inherit from both int and string but I couldnt get that to work probably because the generic versions inherit from the non-generic IEnumerable again making it a diamond shaped inheritance tree. Maybe you can use it as food for thought.
class X : IEnumerable<int>, IEnumerable<string>
{
private int[] i = new int[5];
private string[] s = new string[2];
public X()
{
i[0] = 0; i[1] = 1; i[2] = 2; i[3] = 3; i[4] = 4;
s[0] = "test"; s[1] = "test2";
}
public IEnumerator GetEnumerator()
{
return i.GetEnumerator();
}
IEnumerator<int> IEnumerable<int>.GetEnumerator()
{
return (IEnumerator<int>)i.GetEnumerator();
}
IEnumerator<string> IEnumerable<string>.GetEnumerator()
{
return (IEnumerator<string>)i.GetEnumerator();
}
}
Upvotes: 1