使用 StreamReader 计算重复项?
我现在使用 StreamReader 来读取人名文件,它是一个文本文件,包含人名,所以显然有重复项,我希望能够显示现在有多少人有相同的人名,例如:
josh
alex
josh
john
alex
我想说,
josh 2
alex 2
john 1
但我似乎找不到一种简单的方法来做到这一点,最简单的方法是什么,
I'm using streamreader now to read a file of people names, it is a text file, of people first names, so there are obviously duplicates, and i want to be able to display how many people have the same now so for example:
josh
alex
josh
john
alex
I want it to say,
josh 2
alex 2
john 1
but I can't seem to find an easy way of doing this, what would be the easiest way about doing this,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我会说使用
Dictionary
。当然,解决方案有很多不同的路径,但这就是我解决这个问题的方法。我还没有运行这段代码,但我认为这会对你有所帮助。
I'd say use a
Dictionary<string, int>
.Of course there are many different paths to a solution, but this is how I would tackle it. I haven't run this code yet, but this will help you I think.
使用 LINQ 尝试一下。
首先使用以下代码将文本文件读取到
List
:您需要定义一个类,其中包含名称和相应的计数:
最后使用此
Lambda
表达式以获得所需的List
现在迭代列表以获取名称和重复项的计数。
Try this with LINQ.
First read your text file to a
List<string>
using this code:You need to define a class where you will have name and accordingly the count:
And finally use this
Lambda
expression to get desiredList<string>
Now iterate through the list to get the names and the count of duplicates.
使用 HashMap 可以解决您的问题。
当您读取名称时,检查该密钥是否已经存在,如果存在,则更新它(+1),如果不存在,则将其添加到哈希映射中。
最后,您所需要做的就是打印键值对。
Using an HashMap is a solution to your problem.
When you read a name, check if the key is already present, if so, update it (+1), if not add it to your Hash Map.
In the end, all you need to do is print the key-value pairs.
将所有名称存储在
Dictionary中名称
。对每一行使用类似的内容:(
如果该项目不存在,则应将计数设置为一)
Store all names in a
Dictionary<string, int> names
.Use something like this for each row:
(it should set the count to one if the item do not exist)
当然,您也可以使用 Linq 执行类似的操作(省略错误检查):
根据文件的大小,这可能需要摆脱流;但是,这并不是说如果文件对于内存而言相当大,则应该使用
ReadLine
。You could of course also do something like this (error checking omitted), using Linq:
Depending on the size of the file, this might be desirable to get rid of the stream; however, this isn't to say that if the file was considerably large for memory that you should use
ReadLine
.尝试这个离线解决方案
try this offline solution