Swap two items in List

前端 未结 5 854
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 05:20

Is there a LINQ way to swap the position of two items inside a list?

5条回答
  •  天涯浪人
    2020-11-30 05:54

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

    public static void Swap(IList 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 Swap(this IList list, int indexA, int indexB)
    {
        T tmp = list[indexA];
        list[indexA] = list[indexB];
        list[indexB] = tmp;
        return list;
    }
    

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

提交回复
热议问题