Search code examples
c#linqswap

Swap two items in List<T>


Is there a LINQ way to swap the position of two items inside a List<T>?


Solution

  • Check the answer from Marc from C#: Good/best implementation of Swap method.

    public static void Swap<T>(IList<T> list, int indexA, int indexB)
    {
        T tmp = list[indexA];
        list[indexA] = list[indexB];
        list[indexB] = tmp;
    }
    

    which can be linq-i-fied like

    public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB)
    {
        T tmp = list[indexA];
        list[indexA] = list[indexB];
        list[indexB] = tmp;
        return list;
    }
    

    var lst = new List<int>() { 8, 3, 2, 4 };
    lst = lst.Swap(1, 2);