Rambo Rambo - 1 year ago 157
C# Question

How to sort items in a list using foreach C#

I need to sort the items I have in a list by age using foreach in ascending order, and so I have no idea how to. This is my code so far:

namespace ListProject
public struct FamilyMem
public string name;
public int age;

public FamilyMem(string name,int age)
this.name = name;
this.age = age;

class Program
static void Main(string[] args)
FamilyMem Jack = new FamilyMem("Jack", 15);
FamilyMem Tom = new FamilyMem("Tommy", 24);
FamilyMem Felix = new FamilyMem("Felix", 26);
FamilyMem Lukas = new FamilyMem("Lukas", 26);
FamilyMem Austin = new FamilyMem("Austin", 54);
FamilyMem Ben = new FamilyMem("Ben", 55);

List<FamilyMem> gambleList = new List<FamilyMem>();




I also need a separate piece of code that will allow me to sort the names alphabetically. Thanks.

Answer Source

You can't edit a collection while you're iterating over it with a foreach loop, so this much at least isn't possible. You can, however, use LINQ or some for loops. Use something like:

gambleList = gambleList.OrderBy(item => item.name).ToList();

The reason for the assignment, by the way, is that the OrderBy operation (unlike, for example, the Sort() method) does not sort the collection in place - it returns a reference to a sorted collection.

You could also use a standard for loop or recursive function to implement something like an Insertion Sort.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download