将字典的所有内容写入文件

本文关键字:文件 字典 | 更新日期: 2023-09-27 18:36:07

我有一本字典看起来像这样

public Dictionary<string,List<ForwardBarrelRecord>> lexicon = new Dictionary<string, List<ForwardBarrelRecord>>();

ForwardBarrelRecord看起来像这样

public struct ForwardBarrelRecord
{
    public string DocId;
    public int hits { get; set; }
    public List<int> hitLocation;
}

我想将所有内容写到文件前向桶记录中的 int 列表中。这样当我检索它时,我可以对字典进行精确的重建。

到目前为止,我已经编写了代码,但它只将键保存在字典中,而不是复制值,只是写入类路径。到目前为止,我的代码是

using (var file = new System.IO.StreamWriter("myfile.txt"))
        {
            foreach (var entry in pro.lexicon)
            {
                file.WriteLine("[{0} {1}]", entry.Key, entry.Value);
            }
        }

我希望对我这本字典中的所有内容进行深度复制。

任何帮助将不胜感激。

将字典的所有内容写入文件

如此链接中所述 为什么 .NET 中没有可序列化的 XML 字典?

关于 XML 序列化的事情是,它不仅仅是创建字节流。它还涉及创建此字节流将验证的 XML 架构。XML 架构中没有表示字典的好方法。你能做的最好的事情就是证明有一个唯一的键

但是如果你想要一个工作,你可以试试这个代码我试过了,它工作得很好,你应该手动做的一件事是检查键是否始终是唯一的尝试这样的事情

 class Program
{        
    static void Main(string[] args)
    {
        List<KeyValuePair<string,List<ForwardBarrelRecord>>>  lexicon   = new List<KeyValuePair<string,List<ForwardBarrelRecord>>>();  
        ForwardBarrelRecord FBR = new ForwardBarrelRecord();  
        FBR.DocId ="12"; 
        FBR.hits= 14;  
        FBR.hitLocation = new List<int>(){12,13,114};
        var lst = new List<ForwardBarrelRecord>() { FBR, FBR };
        KeyValuePair<string,List<ForwardBarrelRecord>> t= new KeyValuePair<string,List<ForwardBarrelRecord>>("Test",lst);
        lexicon.Add(t);            
        XmlSerializer serializer = new XmlSerializer(typeof(List<KeyValuePair<string, List<ForwardBarrelRecord>>>));
        string  fileName= @"D:'test'test.xml";
        Stream stream = new FileStream(fileName,FileMode.Create);
        serializer.Serialize(stream,lexicon);
        stream.Close();            
    }     
}
public struct ForwardBarrelRecord
{
    [XmlElement]
    public string DocId;
    [XmlElement]
    public int hits { get; set; }
    [XmlElement]
    public List<int> hitLocation;
}

}但是,如果您想要更强大的解决方案,则可以使用此自定义的SortedDictionary http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx

希望这个帮助