I need a basic example of how to use the IComparable
interface so that I can sort in ascending or descending order and by different fields of the object type I\'m s
Well, since you are using List
it would be a lot simpler to just use a Comparison
, for example:
List data = ...
// sort by name descending
data.Sort((x,y) => -x.Name.CompareTo(y.Name));
Of course, with LINQ you could just use:
var ordered = data.OrderByDescending(x=>x.Name);
But you can re-introduce this in List
(for in-place re-ordering) quite easily; Here's an example that allows Sort
on List
with lambda syntax:
using System;
using System.Collections.Generic;
class Foo { // formatted for vertical space
public string Bar{get;set;}
}
static class Program {
static void Main() {
List data = new List {
new Foo {Bar = "abc"}, new Foo {Bar = "jkl"},
new Foo {Bar = "def"}, new Foo {Bar = "ghi"}
};
data.SortDescending(x => x.Bar);
foreach (var row in data) {
Console.WriteLine(row.Bar);
}
}
static void Sort(this List source,
Func selector) {
var comparer = Comparer.Default;
source.Sort((x,y)=>comparer.Compare(selector(x),selector(y)));
}
static void SortDescending(this List source,
Func selector) {
var comparer = Comparer.Default;
source.Sort((x,y)=>comparer.Compare(selector(y),selector(x)));
}
}