Loop though IList, but with for loop, not for each

c#, for-loop

Solution

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.

Problem

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 } ```

Original source