Generic List - moving an item within the list

前端 未结 10 734
后悔当初
后悔当初 2020-11-28 04:32

So I have a generic list, and an oldIndex and a newIndex value.

I want to move the item at oldIndex, to newIndex.

10条回答
  •  一个人的身影
    2020-11-28 05:21

    This is how I implemented a move element extension method. It handles moving before/after and to the extremes for elements pretty well.

    public static void MoveElement(this IList list, int fromIndex, int toIndex)
    {
      if (!fromIndex.InRange(0, list.Count - 1))
      {
        throw new ArgumentException("From index is invalid");
      }
      if (!toIndex.InRange(0, list.Count - 1))
      {
        throw new ArgumentException("To index is invalid");
      }
    
      if (fromIndex == toIndex) return;
    
      var element = list[fromIndex];
    
      if (fromIndex > toIndex)
      {
        list.RemoveAt(fromIndex);
        list.Insert(toIndex, element);
      }
      else
      {
        list.Insert(toIndex + 1, element);
        list.RemoveAt(fromIndex);
      }
    }
    

提交回复
热议问题