Mom*_*omo 3 c# arrays for-loop
我有一个包含重复值的数组.我需要显示在数组中找到每个值的次数.
让我们说我有一个包含8个值的数组,array = {1,2,3,1,1,2,6,7}我需要输出为:
1 was found 3 times
2 was found 2 times
3 was found 1 time
6 was found 1 time
7 was found 1 time
Run Code Online (Sandbox Code Playgroud)
这是我的代码.现在我将数组中的每个值保存到变量,然后循环遍历数组以检查值是否存在然后将其打印出来.
int[] nums = { 2, 4, 14, 17, 45, 48, 5, 6, 16, 25, 28, 33, 17, 26, 35, 44, 46, 49, 5, 6, 20, 27, 36, 45, 6, 22, 23, 24, 33, 39, 4, 6, 11, 14, 15, 38, 5, 20, 22, 26, 29, 47, 7, 14, 16, 24, 31, 32 };
for (int i = 0; i < nums.Length; i++)
{
int s = nums[i];
for (int j = 0; j < nums.Length; j++)
{
if (s == nums[j])
{
Console.WriteLine(s);
}
}
}
Run Code Online (Sandbox Code Playgroud)
提前致谢
Mar*_*ell 13
foreach(var grp in nums.GroupBy(x => x).OrderBy(grp => grp.Key)) {
Console.WriteLine("{0} was found {1} times", grp.Key, grp.Count());
}
Run Code Online (Sandbox Code Playgroud)
的GroupBy
(通过使用本身作为键的号码将所有的值成组x => x
).对于每个唯一值,我们将拥有一个不同的组,其中包含一个或多个值.将OrderBy
确保我们(通过报告在关键阶组grp => grp.Key
).最后,Count
告诉我们识别出的组中有多少项Key
(原始值,如果您还记得).