I have a List<Player> that I wish to output ordered to a string, so I am wondering what would be the correct way of doing this and if a simple foreach will always output it ordered already (so far it does from the tests I did) ?
For example:
int position = 0;
foreach (var player in list)
{
position++;
Console.Write(position.ToString() + " " + player.Name);
}
Where I could possible later get it like list[X] where X is the player number in the list.
Or are there better ways of doing this ?
A List will output the elements in the order they were added to the list. If you using .net 3.0+ you can execute an
.OrderBy(r=> r.Foo)to guarantee the order prior to printing the output. if your going to be incrementing a counter during your loop, I would suggest using a classic for loop as opposed to a foreach