首页 > 解决方案 > 交换数组的两个特定成员的正确方法是什么?

问题描述

如果这个问题很无聊,我很抱歉,我只学习了 3 周。这有点压倒性,即使你像我一样做简单的事情。

所以我试图创建一个程序来管理“帐户”作为实践,并将用户和相应的密码放在两个单独的 .txt 文件中。每行相应地转换为用户或密码。我同时使用列表和数组,因为数组在某些情况下更容易使用,但列表可以有不同的长度。

我在为程序创建一个函数时遇到了一个问题,该函数将列表中的第一个用户“管理员”更改为一个用户,其 ID 以用户输入的形式给出。我读到了如何做到这一点,但我似乎失败了,因为预期的交换完全没有做任何事情。用户按原始顺序返回列表。也欢迎进一步观察我的代码为何混乱。

这是程序的这个函数的实际代码:

else if (input.Contains("changeadmin"))
{
    foreach (string y in idKeysLocArray) //checks every line for username
    {
        if (input.Contains(y))
        {
            string[] idKeysLocArray2 = File.ReadAllLines(idKeysLoc); // creates new arrays in case .txt was updated by different function before
            string[] passKeysLocArray2 = File.ReadAllLines(passKeysLoc);

            static void Swap(ref string a, ref string b)  // create function to swap two members of an array
            {
                string temp = a;
                a = b;
                b = temp;
            }

            Swap(ref idKeysLocArray2[0], ref idKeysLocArray2[Array.IndexOf(idKeysLocArray2, y)]); //using function to swap array members
            Swap(ref passKeysLocArray2[0], ref passKeysLocArray2[Array.IndexOf(idKeysLocArray2, y)]);

            var idKeysLocArray2List = idKeysLocArray2.ToList();
            var passKeysLocArray2List = passKeysLocArray2.ToList();

            foreach (string h in idKeysLocArray2List) // to check success
            { 
                Console.WriteLine(h);
            }
            TextWriter w7 = new StreamWriter(idKeysLoc); // write swapped values to .txt file
            foreach (string s in idKeysLocArray2List)
                w7.WriteLine(s);

            w7.Close();

            TextWriter w8 = new StreamWriter(passKeysLoc);
            foreach (string s in passKeysLocArray2List)
                w8.WriteLine(s);

            w8.Close();
        }
    }
}

标签: c#arraysswap

解决方案


推荐阅读