Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

for-loop

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
}
like image 441
Stefan Steiger Avatar asked Dec 23 '22 06:12

Stefan Steiger


1 Answers

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.

like image 104
Erich Avatar answered Jan 01 '23 10:01

Erich