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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
AlanRank #669 · 3.6K reputationPosted Dec 4, 2008, 4:55 AM EST
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 AlfordRank #1,411 · 1.2K reputationPosted Dec 4, 2008, 5:00 AM EST
1. Your class will need to implement the IComparable interface...
2. You need to implement the IComparable method in your class.
int IComparable.CompareTo(object obj){ YourClassName Compare = (YourClassName)obj; int result = this.YourSortingProperty.CompareTo(Compare.YourSortingProperty); if (result == 0) result = Compare.YourSortingProperty.CompareTo(this.YourSortingProperty); return result;}3. and the code to sort...