将 KeyValuePair 列表的内容写入文本文件 - 有一个问题

发布于 2024-10-21 16:29:45 字数 342 浏览 2 评论 0原文

将列表中可用的“值”写入文本文件的最佳方法是什么?问题是文本文件的名称应该由密钥确定。

例如,我设法构建了一个这样的列表:

["Animal", "Lion|Roars"]
["Animal", "Tiger|Roars"]
["Bird",   "Eagle|Flies"]
["Bird",   "Parrot|Mimics"]

我们需要根据上述内容编写两个文件:Animal.txtBird.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

看春风乍起 2024-10-28 16:29:45

我会使用 LINQ 进行分组,然后将每个组一次写入一个文件。
像这样简单的事情应该可以做到:

    static void WriteFiles(IEnumerable<KeyValuePair<string, string>> data)
    {
        foreach (var group in from kvp in data
                              group kvp.Value by kvp.Key)
            File.WriteAllLines(group.Key + ".txt", group);
    }

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:

    static void WriteFiles(IEnumerable<KeyValuePair<string, string>> data)
    {
        foreach (var group in from kvp in data
                              group kvp.Value by kvp.Key)
            File.WriteAllLines(group.Key + ".txt", group);
    }
ゝ杯具 2024-10-28 16:29:45
foreach (var group in yourList.GroupBy(x => x.Key, x => x.Value))
{
    File.WriteAllLines(group.Key + ".txt", group);
}
foreach (var group in yourList.GroupBy(x => x.Key, x => x.Value))
{
    File.WriteAllLines(group.Key + ".txt", group);
}
物价感观 2024-10-28 16:29:45

您可以尝试分组:

class Program
{
    static void Main()
    {
        var data = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("Animal", "Lion|Roars"),
            new KeyValuePair<string, string>("Animal", "Tiger|Roars"),
            new KeyValuePair<string, string>("Bird", "Eagle|Flies"),
            new KeyValuePair<string, string>("Bird", "Parrot|Mimics")
        };
        var groups = data.GroupBy(x => x.Key);
        foreach (var group in groups)
        {
            var filename = Path.ChangeExtension(group.Key, "txt");
            var content = string.Join(Environment.NewLine, group.Select(x => x.Value));
            File.WriteAllText(filename, content);
        }
    }
}

这将生成:

  1. Animal.txt:

    狮子|咆哮
    老虎|咆哮
    
  2. Bird.txt

    鹰|苍蝇
    鹦鹉|模仿者
    

You may try grouping:

class Program
{
    static void Main()
    {
        var data = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("Animal", "Lion|Roars"),
            new KeyValuePair<string, string>("Animal", "Tiger|Roars"),
            new KeyValuePair<string, string>("Bird", "Eagle|Flies"),
            new KeyValuePair<string, string>("Bird", "Parrot|Mimics")
        };
        var groups = data.GroupBy(x => x.Key);
        foreach (var group in groups)
        {
            var filename = Path.ChangeExtension(group.Key, "txt");
            var content = string.Join(Environment.NewLine, group.Select(x => x.Value));
            File.WriteAllText(filename, content);
        }
    }
}

which would generate:

  1. Animal.txt:

    Lion|Roars
    Tiger|Roars
    
  2. Bird.txt:

    Eagle|Flies
    Parrot|Mimics
    
拥有 2024-10-28 16:29:45

您不需要尝试对所有内容进行 linqify。创建分组时,您可以根据列表中的所有数据创建一个字典,然后才能将一行写入输出。这将消耗至少两倍的内存。
这种设计消除了惰性处理,因为您在写入输出之前急切地将所有内容读入内存。

相反,您可以一一处理列表并将当前行写入正确的文件。这可以像通过使用 Animal 或 Bird 作为键来选择正确的输出文件来查找正确的文件流的哈希表一样简单。

static Dictionary<string, StreamWriter> _FileMap = new Dictionary<string, StreamWriter>();

static void Main(string[] args)
{
    var data = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("Animal", "Lion|Roars"),
        new KeyValuePair<string, string>("Animal", "Tiger|Roars"),
        new KeyValuePair<string, string>("Bird", "Eagle|Flies"),
        new KeyValuePair<string, string>("Bird", "Parrot|Mimics")
    };

    foreach (var line in data) // write data to right output file
    {
        WriteLine(line.Key, line.Value);
    }

    foreach (var stream in _FileMap) // close all open files
    {
        stream.Value.Close();
    }
}

static void WriteLine(string key, string line)
{
    StreamWriter writer = null;
    if (false == _FileMap.TryGetValue(key, out writer))
    {
        // Create file if it was not opened already
        writer = new StreamWriter(File.Create(key+".txt"));
        _FileMap.Add(key,writer);
    }
    writer.WriteLine(line);  // write dynamically to the right output file depending on passed key
}

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.

static Dictionary<string, StreamWriter> _FileMap = new Dictionary<string, StreamWriter>();

static void Main(string[] args)
{
    var data = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("Animal", "Lion|Roars"),
        new KeyValuePair<string, string>("Animal", "Tiger|Roars"),
        new KeyValuePair<string, string>("Bird", "Eagle|Flies"),
        new KeyValuePair<string, string>("Bird", "Parrot|Mimics")
    };

    foreach (var line in data) // write data to right output file
    {
        WriteLine(line.Key, line.Value);
    }

    foreach (var stream in _FileMap) // close all open files
    {
        stream.Value.Close();
    }
}

static void WriteLine(string key, string line)
{
    StreamWriter writer = null;
    if (false == _FileMap.TryGetValue(key, out writer))
    {
        // Create file if it was not opened already
        writer = new StreamWriter(File.Create(key+".txt"));
        _FileMap.Add(key,writer);
    }
    writer.WriteLine(line);  // write dynamically to the right output file depending on passed key
}
与之呼应 2024-10-28 16:29:45

因此,您已经

List<KeyValuePair<string, string>> keyValuePairs;

并且想要根据每对的 Key 属性将它们写入文件。好的,只需按 Key 分组并根据 Key 附加到文件名即可。

var groups = keyValuePairs.GroupBy(x => x.Key);
foreach(var group in groups) {
    File.AppendAllLines(
        GetFilenameFromKey(group.Key),
        group.Select(x => x.Value)
    );
}

这里,GetFilenameFromKey 的简单版本是

public string GetFilenameFromKey(string key) {
    return Path.ChangeExtension(key, "txt");
}

So you have

List<KeyValuePair<string, string>> keyValuePairs;

and you want to write these to a file, based on the Key property for each pair. Fine, just group by the Key and append to the filename based on the Key.

var groups = keyValuePairs.GroupBy(x => x.Key);
foreach(var group in groups) {
    File.AppendAllLines(
        GetFilenameFromKey(group.Key),
        group.Select(x => x.Value)
    );
}

Here, a naive version of GetFilenameFromKey is

public string GetFilenameFromKey(string key) {
    return Path.ChangeExtension(key, "txt");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文