views:

126

answers:

4

Hi I have a for loop where i want to orderby the name alphabetically

a b c d

looking how to do this, wondered even if i could use linq orderby inside the forloop?

+13  A: 

Try this:

List<Item> myItems = new List<Item>();
//load myitems
foreach(Item i in myItems.OrderBy(t=>t.name))
{
 //Whatever
}
Abe Miessler
A: 

foreach needs an IEnumerable<T> LINQ order-by takes in one IEnumerable<T> and gives you a sorted IEnumerable<T>. So yes, it should work.

Ben Voigt
A: 
new string[] { "d", "c", "b", "a" }.OrderBy(s => s).ToList().ForEach(s => MessageBox.Show(s));
Pedro
A: 

You don't need a Loop at all. Just use LINQ:

List<MyClass> aList = new List<MyClass>();

// add data to aList

aList.OrderBy(x=>x.MyStringProperty);
awrigley