Skip to content

Instantly share code, notes, and snippets.

@JustinMorgan
Created December 1, 2015 00:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinMorgan/70a84d546f1ce2f36e92 to your computer and use it in GitHub Desktop.
Save JustinMorgan/70a84d546f1ce2f36e92 to your computer and use it in GitHub Desktop.
ForEach and Zip for IDictionary
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