首页 > 解决方案 > c#的算法问题(使用string.split显示每个数字)

问题描述

假设我们有 1 到 20 的整数。我必须打印出如下内容:

Number of 1: 13
Number of 2: 5
Number of 3: 5
.
.
Number of 9: 2

我使用了这样的 string.split 方法。

如何使用整数数组实现这一点并使用 for 循环前进?或者有没有更好的方法来解决这个问题?

标签: c#algorithmsplitnumbersdigits

解决方案


有没有更好的方法来解决这个问题?

是的,有更好的方法来做你想要实现的目标。

这是我的尝试:

我建议使用Dictionary<int, int>数字来存储整数及其计数。

var result = Enumerable.Range(1, 20) //Iterate from 1 to 20
            .SelectMany(x => x.ToString()) //create an array from [1..20]
            .GroupBy(x => x)  //Group by element, so that you will get count
            .ToDictionary(x => x.Key, x => x.Count()); //Store it in dictionary

foreach(var item in result)
    Console.WriteLine($"Number of {item.Key} : {item.Value}");

.NET 小提琴


推荐阅读