Foreach a list or which would be the correct approach?
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开发者_Python百科 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
for(int pos =0; pos<list.count; ++pos) {
Console.Write(pos.ToString() + " " + list[pos].Name);
}
For a list, using foreach will always output in the original order of the list.
What you have works. List is an ordered collection and its enumerator is also ordered. This is a good question to ask because not all collections have a concept of ordering, such as a Dictionary
If by ordered you mean in the order in which it in the collection that your foreach is exactly how I would do it. However, if you need to change the order then you might think about using LINQ, especially if you might want to order by different properties of the plyer class.
精彩评论