tags:

views:

637

answers:

3

I have a IList of objects. They are of type NHibernate.Examples.QuickStart.User. There is also an EmailAddress public string property.

Now I can loop through that list with a for each loop.
Is it possible to loop through a Ilist with a simple for loop?
Because simply treating the IList as an array doesn't seem to work...

System.Collections.IList results = crit.List();

foreach (NHibernate.Examples.QuickStart.User i in results)
{
    Console.WriteLine(i.EmailAddress);
}

for (int i = 0; i < results.Count; ++i)
{
    Console.WriteLine(results[i].EmailAddress); // Not Working
}
+5  A: 

Since you are using a non-Generic IList, you are required to cast the value:

for (int i = 0; i < results.Count; ++i)
    {
        Console.WriteLine(((NHibernate.Examples.QuickStart.User)results[i]).EmailAddress); // Not Working
    }

Alternatively, you could make your IList the Generic version by changing the 1st line to:

System.Collections.IList<NHibernate.Examples.QuickStart.User> results = crit.List();

Note that for this solution, you would have to change the crit.List() function to return this type.

Erich
+1  A: 
for (int i = 0; i < results.Count; ++i)
{
    Console.WriteLine((NHibernate.Examples.QuickStart.User)results[i]).EmailAddress); // Not Working
}

Remember to cast the element type properly, since the IList indexer returns a simple object.

Aviad P.
+1  A: 

You are using a basic IList, which store objects as type Object. If you use a foreach, type casting is done for you automatically. But if you use an indexer as in for (i = 0; i<count... , it is not.

Try this, see if it works:

for (int i = 0; i < results.Count; ++i)
{
    var result = (NHibernate.Examples.QuickStart.User)results[i];
    Console.WriteLine(result.EmailAddress); // Not Working
}

...

chakrit
You mean: `result.EmailAddress`
Stefan Steinegger
Oh, thanks for pointing that out :)
chakrit