Counting repeating numbers in an Array

前端 未结 5 1659
生来不讨喜
生来不讨喜 2020-12-22 02:53

Fairly new to C#. Have an assignment for class that asks us to generate an array from user inputted values. This part is done and work\'s perfectly.

Now that the arr

5条回答
  •  独厮守ぢ
    2020-12-22 03:04

    You can create a dictionary in that the keys are numbers, and the values are counts of that specific number in the array, and then increase the values in the dictionary each time a number is found:

    Example:

            int[] arrayOfNumbers = new int[] { 1, 4, 2, 7, 2, 6, 4, 4, };
            Dictionary countOfItems = new Dictionary();
            foreach (int eachNumber in arrayOfNumbers)
            {
                if (countOfItems.ContainsKey(eachNumber))
                    countOfItems[eachNumber]++;
                else
                    countOfItems[eachNumber] = 1;
            }
    

    This code works in all C# versions, but if you are using C# 3 or greater you could use LINQ, as others are suggesting. =)

提交回复
热议问题