Why I should sort elements before using foreach loop in c# ?

Sajo

Member
Joined
Jul 22, 2020
Messages
17
Programming Experience
Beginner
Hello. I read somewhere that before using foreach loop for list elements it is necessary to use the List.Sort method to sort them before using foreach. For example, to print the elements of a list, we need to use this method first, and then the foreach cycle. My question is: why do we have to use the sort method before applying the foreach cycle to list elements and why I should sort elements in my list?
 
There is no need to sort before using a foreach in C#.

Can you provide a link to where you read this?
 
You would only need to sort before the loop if you wanted the items displayed in sorted order. A binary tree search requires data to be sorted but, other than that, you would only sort if you want the items sorted.
 

Latest posts

Back
Top Bottom