将 KeyValuePair 列表的内容写入文本文件 - 有一个问题
将列表中可用的“值”写入文本文件的最佳方法是什么?问题是文本文件的名称应该由密钥确定。
例如,我设法构建了一个这样的列表:
["Animal", "Lion|Roars"]
["Animal", "Tiger|Roars"]
["Bird", "Eagle|Flies"]
["Bird", "Parrot|Mimics"]
我们需要根据上述内容编写两个文件:Animal.txt和Bird.txt,每个文件仅包含各自的值。
什么是有效的方法来做到这一点?
谢谢 SOF 社区。
What is the optimal way to write the "Values" available in a List to a Text file? The catch is the Text file's name should be determined by the Key.
For example, I managed to construct a List like this:
["Animal", "Lion|Roars"]
["Animal", "Tiger|Roars"]
["Bird", "Eagle|Flies"]
["Bird", "Parrot|Mimics"]
We need to write two files based on the above: Animal.txt and Bird.txt each containing their respective values only.
What is an efficient way to do this?
Thank you SOF community.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我会使用 LINQ 进行分组,然后将每个组一次写入一个文件。
像这样简单的事情应该可以做到:
I would use LINQ to do the grouping, then write each group to a file at once.
Something as simple as this should do it:
您可以尝试分组:
这将生成:
Animal.txt
:Bird.txt
:You may try grouping:
which would generate:
Animal.txt
:Bird.txt
:您不需要尝试对所有内容进行 linqify。创建分组时,您可以根据列表中的所有数据创建一个字典,然后才能将一行写入输出。这将消耗至少两倍的内存。
这种设计消除了惰性处理,因为您在写入输出之前急切地将所有内容读入内存。
相反,您可以一一处理列表并将当前行写入正确的文件。这可以像通过使用 Animal 或 Bird 作为键来选择正确的输出文件来查找正确的文件流的哈希表一样简单。
You do not need to try to linqify everything. When you create a grouping you create from all data in the list a dictionary before you can write a single line to the output. This will consume at least twice as much memory as it is necessary.
This design eliminates lazy processing since you are eagerly reading everything into memory before you can write output.
Instead you can process the list one by one and write to the current line to the right file. This can be as easy as a hash table lookup for the right file stream by using Animal or Bird as keys to choose the right output file.
因此,您已经
并且想要根据每对的
Key
属性将它们写入文件。好的,只需按Key
分组并根据Key
附加到文件名即可。这里,
GetFilenameFromKey
的简单版本是So you have
and you want to write these to a file, based on the
Key
property for each pair. Fine, just group by theKey
and append to the filename based on theKey
.Here, a naive version of
GetFilenameFromKey
is