int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
int count = 0;
for (int j = 0; j < array.Length; j++)
{
if (array[i] == array[j])
{
count = count + 1;
}
}
Console.WriteLine(array[i] + " repeats " + count + " times");
}
Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)

我不想使用 LINQ!我的问题是,如何只打印一次结果。例如:
10次重复2次
5次重复3次
2次重复2次
...
谢谢。
这是没有 LINQ 的方法:
var dictionary = new Dictionary<int, int>();
foreach (var element in array)
{
dictionary[element] = (dictionary.ContainsKey(element) ? dictionary[element] : 0) + 1;
}
foreach (var pair in dictionary)
{
Console.WriteLine(pair.Key + " repeats " + (pair.Value - 1) + " times");
}
Run Code Online (Sandbox Code Playgroud)
将它与 LINQ 进行比较,您就会知道为什么它很糟糕:
foreach (var number in array.GroupBy(x => x))
{
Console.WriteLine(number.Key + " repeats " + (number.Count() - 1) + " times");
}
Run Code Online (Sandbox Code Playgroud)
编辑:更改count为(count - 1),因为 OP 想要重复次数,而不是计数。
| 归档时间: |
|
| 查看次数: |
16394 次 |
| 最近记录: |