Loop, although an IList, but for a loop, not for everyone

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

Now I can iterate over this list with a for each loop.
Is it possible to iterate over Ilist with a simple loop? Since just treating 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
}
+3
source share
3 answers

Since you are using a non-Generic IList, you need to specify a value:

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

Alternatively, you can make your version of IList Generic by changing the first line to:

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

Note that for this solution you will need to modify the crit.List () function to return this type.

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

, IList object.

+2

You are using a basic IList that stores objects as a type Object. If you use foreach, molding is automatically created for you. 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
}

...

+2
source

Source: https://habr.com/ru/post/1727819/


All Articles