I need to do something like this:
class myClass {
string name;
}
Listl = new List ();
l.getEnumerator();
foreach (; l.movenext(); ) {
print ( l.Current.name);
}
How to use IEnumerator to access the fields of the classes?
thanks.
class myClass {
string name;
}
Listl = new List ();
l.getEnumerator();
foreach (; l.movenext(); ) {
print ( l.Current.name);
}
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
AlanPosted Sep 18, 2007, 4:14 AM
If you don't have to use IEnumerator, then you can simply use the generic List's IndexOf() method to find the index (zero-based) of a given object:
int index = l.IndexOf(c);
Notice that if the same object is added more than once to the List, then IndexOf() returns the index of the first such object.
MarcoPosted Sep 17, 2007, 8:48 PM
class myclass {
public myclass {
}
}
//main
myclass a,b,c,d;
List
l.Add(a); l.Add(b); l.Add(c); l.Add(d);
int index = c.getPositionInList();
Is there a way to retrieve index?
thanks.
AlanPosted Sep 17, 2007, 9:41 AM
You can't stop MoveNext() starting from the beginning (i.e. an index of 0) but you can skip the first 6 iterations using this code:
for (int i = 0 ;ie.MoveNext(); i++)
{
if (i < 6) continue; // skips elements 0 to 5 inclusive of the List
if (ie.Current.Name.ToLower() == "marco")
{
index = i;
break;
}
}
MarcoPosted Sep 17, 2007, 5:08 AM
ie+6 //avoid movenext() for 6 times;
?
AlanPosted Sep 17, 2007, 4:49 AM
As the List.Enumerator class (the underlying IEnumerator for the List class) doesn't expose an 'Index' property, then the best way to do this is to count the elements yourself:
IEnumerator ie = l.GetEnumerator();
int index = -1;
for (int i = 0 ;ie.MoveNext(); i++)
{
if (((myClass)ie.Current).Name.ToLower() == "marco")
{
index = i;
break;
}
}
Console.WriteLine(index); // 0
Incidentally, you can avoid having to cast the IEnumerator to myClass by using the generic interface IEnumerator instead:
IEnumerator ie = l.GetEnumerator();
int index = -1;
for (int i = 0 ;ie.MoveNext(); i++)
{
if (ie.Current.Name.ToLower() == "marco")
{
index = i;
break;
}
}
Console.WriteLine(index); // 0
MarcoPosted Sep 16, 2007, 8:52 PM
And if I wanna do this how to do?
for ( ;ie.MoveNext(); )
{
if ((myClass)ie.Current).Name == "marco"
int index = (int) ie;
}
Is there a way ?
AlanPosted Sep 16, 2007, 7:27 PM
Try this:
using System;
using System.Collections;
using System.Collections.Generic;
class Program l = new List();
{
static void Main()
{
List
myClass m = new myClass();
m.Name = "Marco";
l.Add(m);
m = new myClass();
m.Name = "Alan";
l.Add(m);
IEnumerator ie = l.GetEnumerator();
for ( ;ie.MoveNext(); )
{
Console.WriteLine(((myClass)ie.Current).Name);
}
Console.ReadKey();
}
}
public class myClass
{
string name;
public string Name
{
get {return name;}
set {name = value;}
}
}