Define a comparer implemeting IComparer<T>
Interface:
public class PersonComparer : IComparer<Person>
{
public int Compare(Person x, Person y)
{
return x.Name.CompareTo(y.Name);
}
}
And use SortedSet<T>
Class then:
SortedSet<Person> list = new SortedSet<Person>(new PersonComparer());
list.Add(new Person { Name = "aby", Age = "1" });
list.Add(new Person { Name = "aab", Age = "2" });
foreach (Person p in list)
Console.WriteLine(p.Name);
If you are limited to usinf .NetFramework3.5, you could use SortedList<TKey, TValue>
Class then:
SortedList<string, Person> list =
new SortedList<string, Person> (StringComparer.CurrentCulture);
Person person = new Person { Name = "aby", Age = "1" };
list.Add(person.Name, person);
person = new Person { Name = "aab", Age = "2" };
list.Add(person.Name, person);
foreach (Person p in list.Values)
Console.WriteLine(p.Name);
Espesially read the Remarks section in the MSDN artcile, comparing this class and SortedDictionary<TKey, TValue>
Class
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…