c# - How can I make Dictionary a general IEnumerable for Factory Design Pattern -
i'm developing simple wpf phone book application uses xml data. idea make more general can use sql data instead of xml data if it's required. that's why chose basic factory design pattern.
here's interface (which functions abstact class):
public interface iphonebookdata { dictionary<string,string> getphonebookdata(); }
here's class inherits interface using xml data , returns dictionary:
using system.collections.generic; using phonebook.bl.xml; using phonebook.bl.xml.parserxml; public class phonebookdataxml : iphonebookdata { private string _path; dictionary<string, string> _phonebookdict = new dictionary<string, string>(); public phonebookdataxml(string path) { _path = path; } public dictionary<string, string> getphonebookdata() { var phonebookxml = parsexml.deserialize<phonebookxml>(_path); foreach (var item in phonebookxml.properties) { _phonebookdict.add(item.key, item.value); } return _phonebookdict; } }
here's factory class:
public static class phonebookdatafactory { public static iphonebookdata getphonebookclass(string input) { if (input.tolower().contains("xml")) { return new phonebookdataxml(input); } return null; } }
and here's mainviewmodel class (wpf mvvm) uses factory xml:
public mainviewmodel() { _namelist = new list<string>(); _phonelist = new list<customkeyvaluepair<string, string>>(); //_phonelist = new list<string>(); var phonebookdatainstance = phonebookdatafactory.getphonebookclass("phonebook.xml"); _phonebookdict = phonebookdatainstance.getphonebookdata(); _namelist = _phonebookdict.keys.tolist(); }
i know dictionary inherits icollection inherits ienumerable tried make general , didn't succeed.
i'll thankful if can show me how can "getphonebookdata" return generic collection , convert dictionary or other collection required in future.
you should use icollection<keyvaluepair<string, string>>
_phonebookdict
icollection<keyvaluepair<string, string>> _phonebookdict = new dictionary<string, string>();
and ienumerable<keyvaluepair<string, string>>
return type method getphonebookdata()
public ienumerable<keyvaluepair<string, string>> getphonebookdata() { var phonebookxml = parsexml.deserialize<phonebookxml>(_path); foreach (var item in phonebookxml.properties) { _phonebookdict.add(new keyvaluepair<string, string>(item.key, item.value)); } return _phonebookdict; }
Comments
Post a Comment