" I can sort it into a new list using" no, that's not the case, OrderBy
doesnt return a list, you have to call ToList
to create a new list. Is your question how to use List.Sort
with an IList<T>
instead of a List<T>
?
You can write an extension method for IList<T>
:
public static IList<T> Sort<T>(this IEnumerable<T> sequence, IComparer<T> comparer = null)
{
var seqList = sequence as List<T>;
if (seqList != null)
{
seqList.Sort((IComparer<T>)comparer);
return seqList;
}
var seqArray = sequence as T[];
if (seqArray != null)
{
Array.Sort(seqArray, (IComparer<T>)comparer);
return seqArray;
}
return sequence.OrderBy(t => t, (IComparer<T>)comparer).ToList();
}
Now you can use Sort
on lists, arrays or any other kind of sequence:
IList<string> strings = new[] { "B", "A", "C" };
strings.Sort();
Update: if you just want one for arrays or lists you can use:
public static void Sort<T>(this IList<T> sequence, IComparer<T> comparer = null)
{
var seqList = sequence as List<T>;
if (seqList != null)
{
seqList.Sort((IComparer<T>)comparer);
return;
}
var seqArray = sequence as T[];
if (seqArray != null)
{
Array.Sort(seqArray, (IComparer<T>)comparer);
}
}