using System.Collections.Generic; public static class ListUtil { /// <summary> /// Replace Index1 and index2 /// </summary> public static void Replace<T>(this IList<T> self, int index1, int index2) { if (self.Count <= index1 || self.Count <= index2) return; var cache = self[index1]; self[index1] = self[index2]; self[index2] = cache; } }
サンプル
using System.Collections.Generic; private void Sample() { var list = new List<int>() { 1, 2, 3, 4, 5 }; // 5, 2, 3, 4, 1 list.Replace(0, 4); }
Tuple を利用した入れ替え
Tuple が利用できるのであれば拡張せずに以下のように記述することも可能です
private void Sample() { var list = new List<int>() { 1, 2, 3, 4, 5 }; // 5, 2, 3, 4, 1 (list[0], list[4]) = (list[4], list[0]); }