I have a serializable dictionary that I created for a WCF REST web service
[Serializable]
public class jsonDictionary<TKey, TValue> : ISerializable
{
private Dictionary<TKey, TValue> _Dictionary;
public jsonDictionary()
{
_Dictionary = new Dictionary<TKey, TValue>();
}
public jsonDictionary(SerializationInfo info, StreamingContext context)
{
_Dictionary = new Dictionary<TKey, TValue>();
}
public TValue this[TKey key]
{
get { return _Dictionary[key]; }
set { _Dictionary[key] = value; }
}
public void Add(TKey key, TValue value)
{
_Dictionary.Add(key, value);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
foreach (TKey key in _Dictionary.Keys)
info.AddValue(key.ToString(), _Dictionary[key]);
}
}
I need to search through this dictionary to determine if 1 of several possible keys are present. I figured I would do this using a foreach statement kinda like so
foreach(var pair in dictionary)
{
switch(pair.key)
{
case "something":
Break;
case "somethingelse":
Break;
}
}
However I keep getting the error:
foreach statement cannot operate on variables of type 'ZTERest.jsonDictionary<string,string>' because 'ZTERest.jsonDictionary<string,string>' does not contain a public definition for 'GetEnumerator'
I know I have to do something with the IEnumerable or IEnumerator interface but I’m not sure how.
A dictionary provides a key/value lookup for a reason, it’s not something that you usually iterate through. The generic
Dictionary<>object that your class is wrapping already has a method calledContainsKey()that will do exactly what you’re looking for, without the overhead of going through every single key/value pair to see if it’s there. There’s no need to expose an iterator, just add this to your class.And call it like this.