How to Return Generic Dictionary in a WebService

后端 未结 5 1602
说谎
说谎 2020-12-09 03:08

I want a Web Service in C# that returns a Dictionary, according to a search:

Dictionary GetValues(string search) {}

The

5条回答
  •  天涯浪人
    2020-12-09 03:53

    I use this util class for serializing dictionaries, maybe it can be useful for you

    using System.Collections.Generic;
    using System.Xml;
    using System.Xml.Schema;
    using System.Xml.Serialization;
    
    namespace Utils {
        ///
        ///
        public class SerializableDictionary : IXmlSerializable {
            private readonly IDictionary dic;
            public DiccionarioSerializable() {
                dic = new Dictionary();
            }
            public SerializableDictionary(IDictionary dic) {
                this.dic = dic;
            }
            public IDictionary Dictionary {
                get { return dic; }
            }
            public XmlSchema GetSchema() {
                return null;
            }
            public void WriteXml(XmlWriter w) {
                w.WriteStartElement("dictionary");
                foreach (int key in dic.Keys) {
                    string val = dic[key];
                    w.WriteStartElement("item");
                    w.WriteElementString("key", key.ToString());
                    w.WriteElementString("value", val);
                    w.WriteEndElement();
                }
                w.WriteEndElement();
            }
            public void ReadXml(XmlReader r) {
                if (r.Name != "dictionary") r.Read(); // move past container
                r.ReadStartElement("dictionary");
                while (r.NodeType != XmlNodeType.EndElement) {
                    r.ReadStartElement("item");
                    string key = r.ReadElementString("key");
                    string value = r.ReadElementString("value");
                    r.ReadEndElement();
                    r.MoveToContent();
                    dic.Add(Convert.ToInt32(key), value);
                }
            }
        }
    }
    

提交回复
热议问题