How can I sort an IEnumerable alphabetically. Is this possible?
Edit: How would I write an in-place solution?
We can't always do it in-place, but we detect when it's possible:
IEnumerable SortInPlaceIfCan(IEnumerable src, IComparer cmp)
{
List listToSort = (src is List) ? (List)src : new List(src);
listToSort.Sort(cmp);
return listToSort;
}
IEnumerable SortInPlaceIfCan(IEnumerable src, Comparison cmp)
{
return SortInPlaceIfCan(src, new FuncComparer(cmp));
}
IEnumerable SortInPlaceIfCan(IEnumerable src)
{
return SortInPlaceIfCan(src, Comparer.Default);
}
This uses the following handy struct:
internal struct FuncComparer : IComparer
{
private readonly Comparison _cmp;
public FuncComparer(Comparison cmp)
{
_cmp = cmp;
}
public int Compare(T x, T y)
{
return _cmp(x, y);
}
}