C# 将词典的所有内容写入文件
我有一本类似这样的字典C# 将词典的所有内容写入文件,c#,.net,file,file-io,dictionary,C#,.net,File,File Io,Dictionary,我有一本类似这样的字典 public Dictionary<string,List<ForwardBarrelRecord>> lexicon = new Dictionary<string, List<ForwardBarrelRecord>>(); public struct ForwardBarrelRecord { public string DocId; public int hits { get; set; }
public Dictionary<string,List<ForwardBarrelRecord>> lexicon = new Dictionary<string, List<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);
}
}
我想把我这本字典里的每一件东西都复制一份
如有任何帮助,将不胜感激。如本链接所述 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;
}
类程序
{
静态void Main(字符串[]参数)
{
列表词典=新列表();
ForwardBarrelRecord FBR=新的ForwardBarrelRecord();
FBR.DocId=“12”;
FBR.hits=14;
FBR.hitLocation=新列表(){12,13114};
var lst=new List(){FBR,FBR};
KeyValuePair t=新的KeyValuePair(“测试”,lst);
词库。加(t);
XmlSerializer serializer=新的XmlSerializer(typeof(List));
字符串文件名=@“D:\test\test.xml”;
Stream=新文件流(文件名,FileMode.Create);
序列化(流、词典);
stream.Close();
}
}
公共结构ForwardBarrelRecord
{
[XmlElement]
公共字符串DocId;
[XmlElement]
公共int命中{get;set;}
[XmlElement]
公共位置列表;
}
}
但是如果您想要一个更健壮的解决方案,您可以使用这个定制的SortedDictionary
希望此帮助您可以重写
ToString
方法以获取对象的字符串表示形式,如果您将数据保存为XML格式而不是文本文件会更好,它将为您提供更容易处理的选项,请考虑将序列化作为一种替代方法。您应该在此处看到:如果您正在寻找“深度复制”(深度克隆)-有很多问题需要讨论。在这种情况下,以文本形式编写可能不是最好的方法-我相信二进制序列化更快更容易。