Returning Key/Value pairs from a .NET Web Service
As soon as I started using Web Services I came against this problem, and loads of other people have asked it before but I didn’t really find a satisfactory answer. The easiest method is to create your own custom class (or a struct, as I did) and use that:
The struct
public struct KeyValueStruct
{
private int _key;
private string _val;
public int Key
{
get { return _key; }
set { _key = value; }
}
public string Value
{
get { return _val; }
set { _val = value; }
}
public KeyValueStruct(int key, string value)
{
_key = key;
_val = value;
}
}
The web method
[WebMethod]
[XmlInclude(typeof(KeyValueStruct))]
public List<KeyValueStruct> GetEnergySources()
{
List<KeyValueStruct> sources = new List<KeyValueStruct>();
sources.Add(new KeyValueStruct(1, "Solar"));
sources.Add(new KeyValueStruct(2, "Wind"));
return sources;
}
Simple!