How do I swap 2 elements in a list [duplicate]

佐手、 提交于 2019-12-06 07:48:32

To swap the values of two variables, the easiest method is using references. This is a classic pointer exercise in c++, but it can apply to C# as well.

// Replace int with any data type / class you need
void Swap (ref int a, ref int b)
{
   int c = a; 
   a = b; 
   b = c;
}

The algorithm used is very simple, and the explanation is usually done like this: you have two glasses, one with water, and one with oil. To put the oil in the first glass, you will need to use a third glass, put the water inside, then put the oil in the first glass, and the water in the second one.


Here is what I had in mind. Look for the comments, so you can understand what's going on.:

// Unlike foreach, with for I can change the values in the list
for (int i = 0; i < inventory.Count; i++)
{
    if (mouseRectangle.Intersects(inventory[i].ItemRectangle))
    {
        if (Input.EdgeDetectLeftMouseDown())
        {
            // You can replace the switch with this shorter structure
            // if A is a bool value, !A will have the opposite value
            inventory[i].ItemSelected = !inventory[i].ItemSelected;
        }  
    }
    else if (Input.EdgeDetectLeftMouseDown())
    {
        // You don't need a case-switch for a single condition. An if should suffice
        if (inventory[i].ItemSelected) 
            inventory[i].ItemSelected = false;
    }
    else if (inventory[i].ItemSelected == true)
    {
        inventory[i].ItemPosition = new Vector2(mouseRectangle.X, mouseRectangle.Y);
        inventory[i].ItemRectangle = new Rectangle(mouseRectangle.X, mouseRectangle.Y, 32, 32);
    }
    else if (inventory[i].ItemSelected == false && //a lot of checks to determine it is not intersecting with an equip slot
    {
        inventory[i].ItemPosition = inventory[i].OriginItemPosition;
        inventory[i].ItemRectangle = inventory[i].OriginItemRectangle;
    }

    // Something definitely wrong with this line, a rectangle to instersect with itself??
    else if (inventory[i].ItemRectangle.Intersects(inventory[PROBABLY_SOMETHING_ELSE].ItemRectangle))
    {
        Swap (ref inventory[i], ref inventory[PROBABLY_SOMETHING_ELSE])
    }
}

To swap an element of the list you can write an extension method as.

public static class ExtensionMethods
{
    public static void Swap<T>(this List<T> list, int index1, int index2)
    {
         T temp = list[index1];
         list[index1] = list[index2];
         list[index2] = temp;
    }
}

Remember to put the extension method inside a static class.

then you can do:

yourList.Swap(0,1); // swap element at index 0 with element at index 1
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!