4

I have a list of object type in c#. Now I want to get values of each element using for loop . I have searched a lot on web but I always found only foreach loop method.

6
  • 1
    What is your exact question ? Commented Jan 27, 2016 at 21:20
  • 2
    What is wrong with the foreach approach? Commented Jan 27, 2016 at 21:21
  • 3
    Your question is very vague. Please add some source code to illustrate the problem. Commented Jan 27, 2016 at 21:21
  • my question is i have a list (List<point> li=new List<point>(); where point is a class and it has two attributes xcor and ycor ) now i want fetch the values of these attributes using for loop. In java we can use something like li.get(index).getxcor(); but in c# i haven't find any such method Commented Jan 27, 2016 at 21:24
  • You can get your object by using point p = li[i]; Commented Jan 27, 2016 at 21:25

2 Answers 2

3

You can loop over a list using for like shown below, although using foreach is generally cleaner

for (var i = 0; i < list.Count; i++) {
    var xcor = list[i].xcor;
    var ycor = list[i].ycor;
}

The equivalent foreach loop would look like this:

foreach (var point in list)
{
   var xcor = point.xcor;
   var ycor = point.ycor
}
Sign up to request clarification or add additional context in comments.

Comments

2

This is how you would get each object in a list of objects with a for loop

List<object> list = new List<object>();

 for (int i = 0; i < list.Count; i++)
 {
      SomeMethodThatDoesSomethingWithAnObject(list[i]);
 }

2 Comments

this would just iterate over the collection and pass the loop counter to the method. Did you mean to pass list[i] as the argument? I would also use a foreach over a for loop, however this is just preference.
yes I did. Thanks for catching that. I edited my post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.