views:

74

answers:

2

This is my KeyValue collection

KeyValuePairCollection<int,string> KV=new KeyValuePairCollection<int,string>();
KV.Key = 1;
KV.Value = "Chapter1";
KV.Key = 2;
KV.Value = "Chapter2";
KV.Key = 3;
KV.Value="Chapter3";


I serialized the collection using the code below

StreamWriter txtWrt=null;
string m_ArraylstfileName = @"d:\XML\GenericsKV.xml";
XmlSerializer xmlPerSerlzr = 
    new XmlSerializer(typeof(KeyValuePairCollection<int,string>));
txtWrt = new StreamWriter(m_ArraylstfileName);
xmlPerSerlzr.Serialize(txtWrt, KV);

My xml file stores the final entry only ( i.e Key=3 ,Value="chapter3" )


Suggestion please.

A: 

Yes... because you override the key and the value always in your code. I assume you want to use a dictionary?

Dictionary<int,string> dic = new Dictionary<int, string>();

dic.Add(1,"Chap 1");
dic.Add(2, "Chap 2");
dic.Add(3, "Chap 3");
gsharp
+1  A: 

each time you set the Key and Value property you overwrite the previous values not add new one, that is why you have only the last one serialized.

So this is not related to serialization, if you want to keep more than one pair use Dictionary

Dictionary<int,string> KV = new Dictionary<int,string>();
KV.Add(1,"a");
KV.Add(2,"b");
foreach (KeyValuePair<int, string> kvp in KV) 
{

}
Ahmed Said