Skip to content

class IDictionaryExtensions

nagahoge edited this page Dec 1, 2012 · 4 revisions

IDictionary#Each<K, V>(Action<K, V> block)

Example

var dict = new Dictionary<string, int>()
{
    {"one", 1},
    {"two", 2},
    {"three", 3}
};

dict.Each((key, val) => Console.WriteLine("key: " + key + ", val: " + val));

If write same logick in C# basic expression.

var dict = new Dictionary<string, int>()
{
    {"one", 1},
    {"two", 2},
    {"three", 3}
};

foreach (KeyValuePair<string, int> pair in dict)
{
    Console.WriteLine("key: " + pair.Key + ", val: " + pair.Value);
}

IDictionary#EachWithCount<K, V>(Action<K, V, long> block)

Example

var dict = new Dictionary<string, int>()
{
    {"one", 1},
    {"two", 2},
    {"three", 3}
};

dict.EachWithCount((key, val, idx) => 
    Console.WriteLine("number " + idx + "  key: " + key + ", val: " + val));

If write same logick in C# basic expression.

var dict = new Dictionary<string, int>()
{
    {"one", 1},
    {"two", 2},
    {"three", 3}
};

int idx = 0;
foreach (KeyValuePair<string, int> pair in dict)
{
    Console.WriteLine("number" + idx++ + "  key: " + pair.Key + ", val: " + pair.Value);
}

IDictionary#KeepIf<K, V>(Func<K, V, bool> block)

IDictionary#RemoveIf<K, V>(Func<K, V, bool> block)

Keep (or remove) key and value from IDictionary of block condition return true.

Example

var dict = new Dictionary<string, int>()
{
    {"one", 1},
    {"two", 2},
    {"three", 3}
};

dict.KeepIf((key, val) => val % 2 == 0); // dict: {{"two", 2}}

If write same logick in C# basic expression.

var dict = new Dictionary<string, int>()
{
    {"one", 1},
    {"two", 2},
    {"three", 3}
};

IList<string> keysToBeRemoved = new List<string>();

foreach (KeyValuePair<string, int> pair in dict)
{
    if (pair.Value % 2 != 0) keysToBeRemoved.Add(pair.Key);
}

foreach (string key in keysToBeRemoved)
{
    dict.Remove(key);
}