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