Skip to content

Instantly share code, notes, and snippets.

@jrwren
Created September 7, 2011 15:12
Show Gist options
  • Select an option

  • Save jrwren/1200833 to your computer and use it in GitHub Desktop.

Select an option

Save jrwren/1200833 to your computer and use it in GitHub Desktop.
ilist swap and move works on arrays
public static class ListExt //for List<> and IList<>
{
public static IList<T> Swap<T>(this IList<T> source, int oldIndex, int newIndex)
{
var temp = source[oldIndex];
source[oldIndex] = source[newIndex];
source[newIndex] = temp;
return source;
}
public static IList<T> Move<T>(this IList<T> source, int oldIndex, int newIndex)
{
var temp = source[oldIndex];
var min = Math.Min(oldIndex, newIndex);
var max = Math.Max(oldIndex, newIndex);
var chi = oldIndex < newIndex ? (new Func<int, int>(i => i + 1)) : (i => i - 1);
var start = oldIndex < newIndex ? min : max;
var end = oldIndex < newIndex ? max : min;
var compare = oldIndex < newIndex ? new Func<int, bool>(i => i < end) : i => i > end;
for (int i = start; compare(i); i=chi(i))
{
source.Swap(i, chi(i));
}
return source;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment