ASP said:
I have a generic list of objects. These objects have a text field that
contains a letter for the first character and numbers for the next three.
For example, "A001".
I need to sort these by letter first and then by number. What is the best
way to sort these?
Any help would be greatly appreciated.
You can either use a Comparison delegate or have your object implement
IComparer.
Here's an example using a comparison:
class Program
{
static void Main(string[] args)
{
List<MyObject> list = new List<MyObject>();
list.Add(new MyObject("Z001"));
list.Add(new MyObject("A100"));
list.Add(new MyObject("C234"));
list.Add(new MyObject("B224"));
list.Sort(new Comparison<MyObject>(compareMethod));
foreach (MyObject myObject in list)
Console.WriteLine(myObject.TextField);
Console.ReadLine();
}
static int compareMethod(MyObject one, MyObject two)
{
return String.Compare(one.TextField, two.TextField);
}
private class MyObject
{
private string textField;
public MyObject(string textField)
{
this.textField = textField;
}
public string TextField
{
get
{
return this.textField;
}
}
}
}
Output:
A100
B224
C234
Z001
Hope this helps.
Dan Manges