Hi.
I have a List
MyObj has a attribute Called Name.
I would like to sort the List i alpfabetical order on the Name attribute.. How do I do that?
Best regards
Peter
Hi.
I have a List
MyObj has a attribute Called Name.
I would like to sort the List i alpfabetical order on the Name attribute.. How do I do that?
Best regards
Peter
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
AlanPosted Dec 4, 2008, 9:55 AM
Do you really mean an attribute or do you mean a property called Name?
If it's the latter, then this approach should work (.NET 2.0 or later):
using System;
using System.Collections.Generic;
class Program list = new List();
{
static void Main()
{
List
list.Add(new MyObj("Peter"));
list.Add(new MyObj("Alan"));
list.Add(new MyObj("Joe"));
list.Add(new MyObj("Fred"));
list.Sort(CompareByName);
foreach(MyObj obj in list)
{
Console.WriteLine(obj.Name);
}
Console.ReadKey();
}
static int CompareByName(MyObj obj1, MyObj obj2)
{
// compare names ignoring case
return String.Compare(obj1.Name, obj2.Name, true);
}
}
class MyObj
{
string name;
public string Name
{
get { return name;}
}
public MyObj(string name)
{
this.name = name;
}
}
Ryan AlfordPosted Dec 4, 2008, 10:00 AM
1. Your class will need to implement the IComparable interface...
2. You need to implement the IComparable method in your class.
3. and the code to sort...