Scoped Dictionary : Dictionary « Collections Data Structure « C# / C Sharp






Scoped Dictionary

        
namespace Ngs.Collections
{
    // Copyright (c) Microsoft Corporation.  All rights reserved.
    // This source code is made available under the terms of the Microsoft Public License (MS-PL)

    using System;
    using System.Collections;
    using System.Collections.Generic;

    public class ScopedDictionary<TKey, TValue>
    {
        ScopedDictionary<TKey, TValue> previous;
        Dictionary<TKey, TValue> map;

        public ScopedDictionary(ScopedDictionary<TKey, TValue> previous)
        {
            this.previous = previous;
            this.map = new Dictionary<TKey, TValue>();
        }

        public ScopedDictionary(ScopedDictionary<TKey, TValue> previous, IEnumerable<KeyValuePair<TKey, TValue>> pairs)
            : this(previous)
        {
            foreach (var p in pairs)
            {
                this.map.Add(p.Key, p.Value);
            }
        }

        public void Add(TKey key, TValue value)
        {
            this.map.Add(key, value);
        }

        public bool TryGetValue(TKey key, out TValue value)
        {
            for (ScopedDictionary<TKey, TValue> scope = this; scope != null; scope = scope.previous)
            {
                if (scope.map.TryGetValue(key, out value))
                    return true;
            }
            value = default(TValue);
            return false;
        }

        public bool ContainsKey(TKey key)
        {
            for (ScopedDictionary<TKey, TValue> scope = this; scope != null; scope = scope.previous)
            {
                if (scope.map.ContainsKey(key))
                    return true;
            }
            return false;
        }
    }
}

   
    
    
    
    
    
    
    
  








Related examples in the same category

1.Dictionary(TKey, TValue) represents a collection of keys and values.
2.Try to add duplicate entry to Dictionary
3.Change value for a key
4.The indexer throws an exception if the requested key is not in the dictionary.
5.Use TryGetValue to get a value out
6.ContainsKey can be used to test keys before inserting them
7.for each KeyValuePair
8.To get the values alone, use the Values property
9.To get the keys alone, use the Keys property.
10.Use the Remove method to remove a key/value pair.
11.Dictionary List
12.Move and copy Directory
13.An Hashtable-backed dictionary that enumerates Keys and Values in insertion order.
14.Represents a dictionary which stores the values as weak references instead of strong references.
15.Dictionary Pretty Print
16.Clone a Dictionary
17.Merges two dictionaries.