C # list index list

I use the List construct to handle the sequence in which images are drawn in "OnPaint". Now, if my images are reordered (for example, "brought to the front" or ".. back"), I will need to move them to my list. I have problems with this because List does not support a method similar to setIndex () .

So what I am trying to do is basically:

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) } 

I want to be able to change the index. I could “insert” a new element into the list at the index into which it should go, and assign a value, and then delete another “source”. However, this in no way looks elegant.

I would welcome any hints and please excuse me if I missed a thread - I really searched before asking.

Ds.

+4
source share
3 answers

What is ridiculous to take the steps you want to take? If you want to change something in the list (this is a collection of vector style), then you want to insert what you want into a new position and remove from the old one. Exactly what you complain about having to do.

If this really upsets you, write an extension method:

 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); } } 

Edit: Oh, you just want to trade? Simplified (and more efficient):

 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; } } 
+7
source

Well, just sharing is easy:

 BitmapWithProps source = activeImages[sourceIndex]; BitmapWithProps dest = activeImages[destIndex]; activeImages[destIndex] = source; activeImages[sourceIndex] = dest; 

But if you need to move one element and leave all other objects in the same order with respect to each other, you must call RemoveAt and then Insert . It will not be very effective, but if you do not have a large list or you do it very often, it is unlikely to really cause you any problems.

+2
source
 public void swapActiveImageIndex(int sourceIndex, int destIndex) { var source = activeImages.Item[sourceIndex]; var dest = activeImages.Item[destIndex]; activeImages.Item[sourceIndex] = dest; activeImages.Item[destIndex] = source; } 
0
source

All Articles