Stefan Steiger
Stefan Steiger

Reputation: 82186

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

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
}

Upvotes: 4

Views: 14294

Answers (3)

chakrit
chakrit

Reputation: 61518

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
}

...

Upvotes: 2

Aviad P.
Aviad P.

Reputation: 32639

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.

Upvotes: 2

Erich
Erich

Reputation: 3972

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.

Upvotes: 7

Related Questions