列表集索引c#

Igo*_*gor 4 c# arrays list

我正在使用List构造来处理在"OnPaint"中绘制图像的序列.现在,如果我的图像被重新排序(例如"带到前面"或"......后面"),我需要在我的列表中重新定位它们.我这样做很麻烦,因为List不支持类似于setIndex()的方法.

所以我想要做的基本上是:

    private List<BitmapWithProps> activeImages = new List<BitmapWithProps>();

    public void addActiveImage(BitmapWithProps image)
    {
        activeImages.Add(image);
    }

    public BitmapWithProps getActiveImage(int index)
    {
        return activeImages[index];
    }

    public void removeActiveImage(int index)
    {
        activeImages.RemoveAt(index);
    }

    public void removeActiveImage(BitmapWithProps item)
    {
        activeImages.Remove(item);
    }

    public void swapActiveImageIndex(int sourceIndex, int destIndex)
    {
        // what would the code look like in here if I were to swap
        // the 2nd item (1) with the 4th one (3) in a 5-item-List (0 - 4)
    }
Run Code Online (Sandbox Code Playgroud)

我希望能够交换一个索引..那种.我可以在它应该去的索引处"插入"一个新项目并分配值,然后删除另一个"源".然而,它似乎并不优雅.

我很高兴有任何提示,请原谅我,如果我忽略了一个线程 - 我在搜索之前做了搜索.

德尚.

Jon*_*nna 7

做你想做的步骤有什么不雅?如果你想改变List中的某个位置(这是一个矢量样式集合),那么你想要做的就是将它插入新位置并将其从旧位置移除.正是你在抱怨必须做的事情.

如果真的让你心烦意乱,那就写一个扩展方法:

public static void MoveIndex<T>(this List<T> list, int srcIdx, int destIdx)
{
  if(srcIdx != destIdx)
  {
    list.Insert(destIdx, list[srcIdx]);
    list.RemoveAt(destIdx < srcIdx ? srcIdx + 1 : srcIdx);
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑:哦,你只想交换?更简单(也更有效)仍然:

public static void SwapItems<T>(this List<T> list, int idxX, int idxY)
{
  if(idxX != idxY)
  {
    T tmp = list[idxX];
    list[idxX] = list[idxY];
    list[idxY] = tmp;
  }
}
Run Code Online (Sandbox Code Playgroud)