Created
December 1, 2015 00:03
-
-
Save JustinMorgan/70a84d546f1ce2f36e92 to your computer and use it in GitHub Desktop.
ForEach and Zip for IDictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace Extensions | |
{ | |
public static class DictionaryExtensions | |
{ | |
public static void ForEach<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, Action<TKey, TValue> action) | |
{ | |
foreach (var key in dictionary.Keys) | |
{ | |
action.Invoke(key, dictionary[key]); | |
} | |
} | |
public static IEnumerable<TResult> Zip<TKey, TValue, TResult>(this IDictionary<TKey, TValue> dictionary, Func<TKey, TValue, TResult> resultSelector) | |
{ | |
return dictionary.Keys.Zip(dictionary.Values, resultSelector); | |
} | |
} | |
} | |
namespace Tester | |
{ | |
using Extensions; | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
Dictionary<string, int> dict = new Dictionary<string, int> | |
{ | |
{"Foo", 1 }, | |
{"Bar", 2 } | |
}; | |
dict.ForEach((x, y) => Console.WriteLine("ForEach: {0}, {1}", x, y)); | |
Console.WriteLine(string.Join("\n", dict.Zip((x, y) => string.Format("Zip: {0}, {1}", x, y)).ToArray())); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment