在数组中查找重复值并输出所有值

时间:2016-04-04 12:37:48

标签: c# arrays loops

所以我有一些工作代码用于在数组中输出重复值,但是当它在屏幕上输出时它总是一个短,我知道它与下面的代码有关,但我不能把我的手指放在上面。 请注意,我不能使用任何System.Array

for (column = 0; column < WinningScores.Length -1 ; column++) 
{
    if (WinningScores[column] == WinningScores[column + 1]) 
    {
        duplicateScore = WinningScores[column];
        duplicateIndex = column;
        Console.Write("\n Competitor {0} is the Winner with a total of: {1}", 
                      duplicateIndex + 1, 
                      duplicateScore - totalSum);
    }
}

3 个答案:

答案 0 :(得分:3)

您可以尝试使用LINQ:

double[] WinningScores = new double[] { 4, 5, 3, 5 };

var duplicates =
    WinningScores
        .Select((score, index) => new { score, player = index + 1})
        .GroupBy(x => x.score, x => x.player)
        .Where(gxs => gxs.Count() > 1);

这给了我这个结果:

result

您可以看到它与玩家5&amp;和2获得4的重复分数。 private static void encryptFile(string inputFile, string outputFile, string strKey) { try { using (RijndaelManaged aes = new RijndaelManaged()) { byte[] key = Encoding.UTF8.GetBytes(strKey); byte[] IV = Encoding.UTF8.GetBytes(strKey); using (FileStream fsCrypt = new FileStream(outputFile, FileMode.Create)) { using (ICryptoTransform encryptor = aes.CreateEncryptor(key, IV)) { using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write)) { using (FileStream fsIn = new FileStream(inputFile, FileMode.Open)) { int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } } } } } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } }

答案 1 :(得分:1)

您的代码会查找consécutive值中的重复项。 尝试使用此代码在数组中输出重复值。

  for (column = 0; column < WinningScores.Length -1 ; column++) 
     {

        for (int cl= column + 1 ; cl < WinningScores.Length - 1 ; cl++)
            {
               if (WinningScores[column] == WinningScores[cl]) {


                        duplicateScore = WinningScores[column];
                        duplicateIndex = column;
                        Console.Write("\n Competitor {0} is the Winner with a total  of: {1}", duplicateIndex + 1, duplicateScore - totalSum);
              }
             }
         }

答案 2 :(得分:0)

//Starts loop through first element
for(int i = 0; i < arr.length, i++)

//starts at second element in array
for(int j = i + 1; k < arr.length, j++)

//double check my logic though, in a hurry at work so had to post this in a rush.