Is there a way to use orderby in forloop c #?

I have a for loop where I want to sort the name alphabetically

a b c d 

looking at how to do this, I wondered if I can use linq orderby inside forloop?

+7
c # for-loop linq sql-order-by
source share
4 answers

Try the following:

 List<Item> myItems = new List<Item>(); //load myitems foreach(Item i in myItems.OrderBy(t=>t.name)) { //Whatever } 
+31
source share
 new string[] { "d", "c", "b", "a" } .OrderBy(s => s) .ToList() .ForEach(s => MessageBox.Show(s)); 
+2
source share

You do not need a Loop at all. Just use LINQ:

 List<MyClass> aList = new List<MyClass>(); // add data to aList aList.OrderBy(x=>x.MyStringProperty); 
+1
source share

foreach requires an IEnumerable<T> LINQ binding order, takes one IEnumerable<T> and gives you a sorted IEnumerable<T> . So yes, that should work.

0
source share

All Articles