【问题标题】:Writing the Contents of KeyValuePair List to Text Files - with a catch将 KeyValuePair 列表的内容写入文本文件 - 有一个问题
【发布时间】:2011-03-10 04:32:20
【问题描述】:

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

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

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

我们需要根据以上内容编写两个文件:Animal.txtBird.txt,每个文件只包含各自的值。

什么是执行此操作的有效方法?

感谢 SOF 社区。​​p>

【问题讨论】:

    标签: c# generics list key-value


    【解决方案1】:

    我会使用 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);
        }
    

    【讨论】:

      【解决方案2】:
      foreach (var group in yourList.GroupBy(x => x.Key, x => x.Value))
      {
          File.WriteAllLines(group.Key + ".txt", group);
      }
      

      【讨论】:

      • 您的解决方案与我的非常相似。伟大的思想都一样!
      【解决方案3】:

      你可以尝试分组:

      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:

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

        Eagle|Flies
        Parrot|Mimics
        

      【讨论】:

        【解决方案4】:

        您不需要尝试 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
        }
        

        【讨论】:

        • 在不对密钥和文件名进行硬编码的情况下,这个逻辑是否可以工作?
        • 确定我已经更新了代码。动态处理输出文件的逻辑在 WriteLine 方法中。
        【解决方案5】:

        所以你有

        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");
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-01-02
          • 1970-01-01
          • 2018-04-22
          • 1970-01-01
          • 2022-11-25
          • 1970-01-01
          • 1970-01-01
          • 2014-02-28
          相关资源
          最近更新 更多