Here is what I tried but I get this error:
Error CS0029 Cannot implicitly convert type 'ListBoxAndDictionary.CountriesAndCities' to 'System.Collections.Generic.Dictionary<string, System.Collections.Generic.List>'
Here is my code:
private Dictionary<string, List<string>> dictCountryAndCities = new
Dictionary<string, List<string>>();
private void button12_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = "CountriesAndCities";
sfd.DefaultExt = ".xml";
sfd.Filter = "XML (*.xml)|*.xml|All Files (*.*)|*.*";
var sfdResult = sfd.ShowDialog();
if (sfdResult == DialogResult.Cancel)
return;
var container = new CountriesAndCities
{
DictCountriesAndCities = dictCountryAndCities
};
using (var writer = XmlWriter.Create(sfd.FileName))
(new XmlSerializer(typeof(CountriesAndCities))).Serialize(writer, container);
}
private void button11_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.DefaultExt = ".xml";
ofd.Filter = "XML (*.xml)|*.xml|All Files (*.*)|*.*";
var ofdResult = ofd.ShowDialog();
if (ofdResult == DialogResult.Cancel)
return;
dictCountryAndCities = new Dictionary<string, List<string>>();
XmlSerializer serializer = new XmlSerializer(typeof(CountriesAndCities));
using (var reader = new StreamReader(ofd.FileName))
{
dictCountryAndCities = serializer.Deserialize(reader) as CountriesAndCities;
//Error CS0029 Cannot implicitly convert type 'ListBoxAndDictionary.CountriesAndCities' to 'System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>>'
}
//binding DataSource for listBox1
listBox1.DataSource = dictCountryAndCities.Keys.ToList();
}
[Serializable]
[XmlRoot("CountriesAndCities")]
public class CountriesAndCities
{
public List<Country> Name
{
get { return DictCountriesAndCities.Select(x => new Country { CountryName = x.Key, Cities = x.Value }).ToList(); }
set { DictCountriesAndCities = value.ToDictionary(x => x.CountryName, x => x.Cities); }
}
[XmlIgnore]
public Dictionary<string, List<string>> DictCountriesAndCities { get; set; }
}
[Serializable]
public class Country
{
public string CountryName { get; set; }
public List<string> Cities { get; set; }
}