c# - 使用 C# 计算每个字符串在字符串数组中出现的次数
问题描述
为此,我将文本文件中的代码作为字符串派生,并且我想计算每个字符串的频率。我让计数器循环,但如果计数器会多次显示结果。
如何让它识别唯一的字符串? 我希望它显示这个:
数字 1 出现 1 次
数字 2 出现 4 次
数字 4 出现 3 次
但它现在正在显示:
数字 1 出现 1 次
数字 2 出现 4 次
数字 2 出现 4 次
数字 2 出现 4 次
数字 2 出现 4 次
数字 4 出现 3 次
数字 4 出现 3 次
数字 4 出现 3 次
void Start()
{
string Random = "";
// Read text
string Numbers_Path = Application.dataPath + "/Text_Files/Numbers.txt";
string[] Duplicates = File.ReadAllLines(Numbers_Path);
foreach (string number in Duplicates)
{
Random += number;
}
//output display text_file
NumOutput.text = Random + "\n";
Array.Sort(Duplicates);
for (int x = 0; x < Duplicates.Length; x++)
{
count = Duplicates.Count(n => n == Duplicates[x]);
Display += "The number " + Duplicates[x] + " appears " + count + " time/s" + "\n";
}
Results.text = Display;
解决方案
您可以使用Enumerable.GroupBy按值对行进行分组(此处的文本值应该足够了)。例如,
foreach(var number in Duplicates.GroupBy(x=>x))
{
Console.WriteLine($"The number {number.Key} has appeared {number.Count()} times");
}
将解决方案分成几部分,**
第 1 步:从文本文件中读取输入
var Duplicates = File.ReadAllLines(Numbers_Path);
第 2 步:按值对重复集合进行分组
Duplicates.GroupBy(x=>x)
输出:最终结果
The number 1 has appeared 3 times
The number 2 has appeared 2 times
The number 3 has appeared 3 times
The number 5 has appeared 2 times
推荐阅读
- excel - Count和CountIf混淆VBA
- python - 如何使用 Python Selenium 单击网页上的链接?
- javascript - 导入 JavaScript 文件
- opengl - Scrt1.o:交叉编译 mesa3d lib 中的通用 ELF (EM: 62) 中的重定位问题
- kotlin - 如何为 isNullOrEmpty() 函数编写单元测试
- powerbi - WTD、MTD、YTD 每个员工每天使用 DAX 的不同时间戳的工作时间
- postgresql - Aurora Postgres 内存 - Aurora Storage Daemon 使用率高
- html - Bootstrap 的网格布局没有将图像和文本并排放置。请告诉我我做错了什么?
- stream - Jitsi 视频会议到流媒体
- python - 如何在 Python3 中验证 x509 证书