Sorting my custom class in a List<T>

D

DotNetNewbie

Hi,

I have a class that represents a Menu Tab:

public class MenuTab
{
public string Name;
public string Filename;
public int SortOrder;
}


I then load them in a Generic like:


List<MenuTab> menus = new List<MenuTab>();

menus.Add(tab);
// etc.

**Now I want to be able to sort the elements just in case things get
added int he wrong order.

menus.Sort();


How can I make the Collection sort using the SortOrder property of the
MenuTab class?
 
J

Jon Skeet [C# MVP]

DotNetNewbie said:
I have a class that represents a Menu Tab:

public class MenuTab
{
public string Name;
public string Filename;
public int SortOrder;
}

Really with public fields? Can't say I like the look of that much...
anyway, moving on to your actual question :)
I then load them in a Generic like:


List<MenuTab> menus = new List<MenuTab>();

menus.Add(tab);
// etc.

**Now I want to be able to sort the elements just in case things get
added int he wrong order.

menus.Sort();


How can I make the Collection sort using the SortOrder property of the
MenuTab class?

Is it fair to assume that the SortOrder numbers will be *reasonably*
small (so that taking one from another will always give a sane result)?
If so:

C# 2:
menus.Sort(delegate(MenuTab mt1, MenuTab mt2)
{ return mt1.SortOrder-mt2.SortOrder; }
);

C# 3:
menus.Sort( (mt1, mt2) => mt1.SortOrder-mt2.SortOrder );

(Otherwise you should call mt1.SortOrder.CompareTo(mt2.SortOrder)) but
that's a bit longer than it really needs to be.)

Alternatively, in C# 3:

menus = menus.OrderBy(tab => tab.SortOrder).ToList();

Note that that creates a *new* list though - so if you've got anything
else with a reference to the old list, it won't be updated.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top