How To implement for loop as foreach loop [Resolved]

Posted by Kasani007 under C# on 12/21/2015 | Points: 10 | Views : 359 | Status : [Member] | Replies : 3
How to implement for loop as foreach loop

for example:

foreach(var item in empDetails)
{
empId=item.Id;
empName=item.Name;
}



By using for loop how can i implement the same




Responses

Posted by: Sheonarayan on: 12/21/2015 [Administrator] HonoraryPlatinum | Points: 50

Up
1
Down

Resolved
Use like this

for (int i = 0; i < empDetails.Count(); i++)
{
empId = empDetails[i].Id;
empName = empDetails[i].Name
}


Depending on empDetails is list collection or array, you can call either .Count() method or .length property to get the length of items into the collection.

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajnilari2015 on: 12/22/2015 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 50

Up
0
Down

Resolved
Way 1
---------

var itemCount = empDetails.Count;


for(int i=0;i< itemCount;i++)
{
empId=item[i].Id;
empName=item[i].Name;
}



Way 2
-------

int i = 0;

var itemCount = empDetails.Count;

for(;i< itemCount;)
{
empId=item[i].Id;
empName=item[i].Name;
i++;
}


Way 3 (Using Goes To operator)
-------------------------------

var itemCount = empDetails.Count;


for (int i= itemCount; i -- > 0;)
{
empId=item[i].Id;
empName=item[i].Name;
}


Hope this helps.

--
Thanks & Regards,
RNA Team

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajnilari2015 on: 12/22/2015 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 25

Up
0
Down
@Kasani007 Sir, glad that it helped

--
Thanks & Regards,
RNA Team

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response