I am using lambda expressions to sort and search an array in C#. I don\'t want to implement the IComparer interface in my class, because I need to sort and search on multiple m
Well, one option is to create something like ProjectionComparer
instead. I've got a version of that in MiscUtil - it basically creates an IComparer
from a projection.
So your example would be:
int index = Array.BinarySearch(widgets, x,
ProjectionComparer.Create(x => x.foo));
Or you could implement your own extension methods on T[]
to do the same sort of thing:
public static int BinarySearchBy(
this TSource[] array,
TSource value,
Func keySelector)
{
return Array.BinarySearch(array, value,
ProjectionComparer.Create(array, keySelector));
}