c# - c#的算法问题(使用string.split显示每个数字)
问题描述
假设我们有 1 到 20 的整数。我必须打印出如下内容:
Number of 1: 13
Number of 2: 5
Number of 3: 5
.
.
Number of 9: 2
我使用了这样的 string.split 方法。
如何使用整数数组实现这一点并使用 for 循环前进?或者有没有更好的方法来解决这个问题?
解决方案
有没有更好的方法来解决这个问题?
是的,有更好的方法来做你想要实现的目标。
这是我的尝试:
我建议使用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}");
推荐阅读
- ruby-on-rails - Rails 在“ShopifyAPI::Product.delete()”上“无法验证 CSRF 令牌真实性”,但正在处理“ShopifyAPI::Product.find()”
- javascript - 如果我得到应用程序流的 Axios 响应内容类型,如何保存 PDF 格式文件?
- microprocessors - WAW 和 WAR 危害是 RISC 处理器独有的吗?
- android - 更改应用程序语言
- laravel - 如何在cpanel上上传laravel项目?
- css - 如何同时设置最小宽度并换到下一行以进行内容可编辑
- reactjs - 有没有办法重构此代码以使其更简洁?
- ruby-on-rails - 如何仅在用户按搜索时呈现搜索结果
- android-recyclerview - RecyclerView:回收项目时绑定不正确
- python - 在 jedi-vim 中跨文件重构