You can use a SortedSet<T>
, which is new with .NET 4. You can use it on a class that implements IComparable<T>
or you can provide an external comparer via a constructor overload. Example:
class Foo
{
public int Bar { get; set; }
}
class FooComparer : IComparer<Foo>
{
public int Compare(Foo x, Foo y)
{
// add null checking, demo purposes only
return x.Bar.CompareTo(y.Bar);
}
}
...
SortedSet<Foo> sortedFoos = new SortedSet<Foo>(new FooComparer());
sortedFoos.Add(new Foo() { Bar = 2 });
sortedFoos.Add(new Foo() { Bar = 1 });
foreach (Foo foo in sortedFoos)
{
Console.WriteLine(foo.Bar);
}
// Prints 1, 2
Note: This collection behaves like a HashSet<T>
. If you add multiple objects that compare equal, they will be discarded.