This questions involves 2 different implementations of essentially the same code.
First, using delegate to create a Comparison method that can be used as a parameter whe
In your case, advantage of having an IComparer
over Comparision
delegate, is that you can also use it for the Sort method, so you don't need a Comparison
delegate version at all.
Another useful thing you can do is implementing a delegated IComparer
implementation like this:
public class DelegatedComparer : IComparer
{
Func _comparision;
public DelegatedComparer(Func comparision)
{
_comparision = comparision;
}
public int Compare(T a,T b) { return _comparision(a,b); }
}
list.Sort(new DelegatedComparer((foo1,foo2)=>foo1.Bar.CompareTo(foo2.Bar));
and a more advanced version:
public class PropertyDelegatorComparer : DelegatedComparer
{
PropertyDelegatorComparer(Func projection)
: base((a,b)=>projection(a).CompareTo(projection(b)))
}