IEnumerable<KeyValuePair<string, string>> implementation

Rune Funch Søltoft replied to Chris Falter at 25-Apr-08 04:02
The implementation with yield return could look like this

public static IEnumerable<KeyValuePair<string, string>> KeyValuePairs {
                get {
                    MaritalStatus ms = new MaritalStatus(MaritalStatus.Married);
                    foreach (KeyValuePair<string, string> kvp in ms.LookupDict)
                        yield return kvp;
                }
}
There's two main differences to the above implementation. It's documented more clearly that it's "readonly" there's  no way to change the elements in the IEnumerable (unless u really try hard, figuring out the actual implementation, casting/using reflection and then ur on ur own :-) ) the second difference is that the implementation here use lazy evaluation.

writing code like:
var pairs = MaritalStatus.KeyValuePairs;
will not actually execute the foreach loop.
if u later write something like

var enumerator = pairs.GetEnumerator();
var firstKey  = enumerator.MoveNext() ? enumerator.Current.Key : "not found";
u still havent iterated the entire LookupDict but only the first element

hope this clearify my point from the above post



Click here to sign in and reply. You could earn money via our $500 contest just for being helpful.
  Article Discussion: A Good Solution for "Magic String" Data - Chris Falter  06-Mar-08 1:51:03 PM
      Yo, Chris! - Peter Bromberg  06-Mar-08 7:32:13 PM
      a few suggestions - Rune Funch Søltoft  24-Apr-08 5:23:53 AM
          Re: a few suggestions - Chris Falter  24-Apr-08 1:05:57 PM
              IEnumerable<KeyValuePair<string, string>> implementation - Rune Funch Søltoft  25-Apr-08 4:02:16 AM
View Posts