Link to home
Start Free TrialLog in
Avatar of johnkainn
johnkainn

asked on

foreach index

When using foreach is it possible to get the index of the loop when certain condition become true?

For example:
foreach(MyObject o in oList){
     if(o.Id==5){
          //Find index of the oList
    }
}
ASKER CERTIFIED SOLUTION
Avatar of Jon500
Jon500
Flag of Brazil image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of p_davis
p_davis

i understand Jon's 2nd point -- you have to make that unique but it is possible to get the index of the object in the list.

Maybe i am misunderstanding?

i put together a little project with the loading of a list of MyObject and then a little loop that grabs the index of each object in that list.
public partial class Form1 : Form
    {
        List<MyObject> oList = new List<MyObject>();

        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Random r = new Random(1);

            for (int i = 0; i <= 10; i++)
            {
                MyObject mo = new MyObject();
                mo.Id = r.Next(200);
                mo.Description = i.ToString();

                oList.Add(mo);
            }

            foreach (MyObject o in oList)
            {
                Int32 index = oList.IndexOf(o);
                //index now contains the index number of o in the oList.

            }
        }
    }

    public class MyObject
    {
        Int32 id;
        String description;

        public Int32 Id
        { get; set; }

        public string Description
        {
            get;
            set;
        }
    }

Open in new window

@p_Davis,

Perhaps I misunderstand your addition, but what the author was trying to do is obtain the index within the foreach iteration he provided in his example loop. Within that loop, as I had shown, there is not a way to get the index of oList to which o belongs. What I suggested he do, instead, was pretty much what you suggested.

Are we in agreement?

Cheers,
Jon
i need this holiday break =)

it appears we are in agreement.
:)

Have a happy, healthy one.

Cheers,
Jon500