This depends on if you want to sort the list itself, or retrieve the values in sorted order (without changing the list).
To sort the list itself (supposing you have a List<element>
called elements
):
elements.Sort((x, y) => x.priority.CompareTo(y.priority));
// now elements is sorted
.NET 2.0 equivalent:
elements.Sort(
delegate(element x, element y) {
return x.priority.CompareTo(y.priority);
}
);
To get the values in sorted order:
var orderedElements = elements.OrderBy(x => x.priority);
// elements remains the same, but orderedElements will retrieve them in order
There's no LINQ equivalent in .NET 2.0, but you can write your own:
public static IEnumerable<T> OrderBy<T>(IEnumerable<T> source, Comparison<T> comparison) {
List<T> copy = new List<T>(source);
copy.Sort(comparison);
foreach (T item in copy)
yield return item;
}
Usage:
Comparison<element> compareByPriority = delegate(element x, element y) {
return x.priority.CompareTo(y.priority);
};
// unfortunately .NET 2.0 doesn't support extension methods, so this has to be
// expressed as a regular static method
IEnumerable<element> orderedElements = OrderBy(elements, compareByPriority);