如何在列表中切换2个值

时间:2019-07-01 10:37:36

标签: c# generic-list

我不知道我在做什么错。该代码的目的是 更改序列中两个值的位置。

当我在控制台Switch 78 97中输入内容时,它可以很好地完成工作,但反之则不起作用: Switch 97 78

这是完整的代码

static void Main()
{
    List<int> numbers = Console.ReadLine().Split(" ").Select(x => int.Parse(x)).ToList();
    string command;
    while((command = Console.ReadLine())!= "END")
    {
        string[] execute = command.Split();
        string type = execute[0];
        switch (type)
        {
            case "Change":
                int firstNumber = int.Parse(execute[1]);
                int secoundNumber = int.Parse(execute[2]);
                ChangeNumber(firstNumber, secoundNumber, ref numbers);
                    break;
            case "Hide":
                HideNumber(ref numbers, execute);
                    break;
            case "Switch":
                SwitchNumber(ref numbers, execute);
                    break;
            case "Insert":
                InsertNumber(ref numbers, execute);
                    break;
            case "Reverse":
                Reverse(ref numbers, execute);
                break;
        }
    }
    foreach (var item in numbers)
    {
        Console.Write(item + " ");
    }
}

//Switch {paintingNumber} {paintingNumber2} – find the given paintings in the collections 
//if they exist and switch their places.
static void SwitchNumber(ref List<int> numbers, string[] execute)
{
    if (numbers.Contains(int.Parse(execute[1])) && numbers.Contains(int.Parse(execute[2])))
    {
        int paintingNumber1 = int.Parse(execute[1]); // 97
        int paintingNumber2 = int.Parse(execute[2]); // 78
        int temp = int.Parse(execute[1]); // 97
        numbers[numbers.IndexOf(paintingNumber1)] = paintingNumber2; // 5 =  78
        numbers[numbers.IndexOf(paintingNumber2)] = temp; // 6 = 97
    }
}

1 个答案:

答案 0 :(得分:3)

问题在于此调用之后:

numbers[numbers.IndexOf(int.Parse(execute[1]))] = paintingNumber2; // 5 =  78

您实际上将第二个数字移到了第一个数字的位置。如果现在尝试查找第二个数字的索引,则会得到第一个数字的索引:

enter image description here

然后您覆盖了错误的值并以您的初始条件结束

解决方案:您需要在对列表进行任何操作之前获取索引:

int index_1 = numbers.IndexOf(paintingNumber1));
int index_2 = numbers.IndexOf(paintingNumber2);
numbers[index_1] = paintingNumber2; // 5 =  78
numbers[index_2] = paintingNumber1; // 6 = 97