Created
September 7, 2011 15:12
-
-
Save jrwren/1200833 to your computer and use it in GitHub Desktop.
ilist swap and move works on arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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