Created
May 21, 2018 06:45
-
-
Save mattiasflodin/2e1ab731c3c5e0b4d415457fbd8da7b8 to your computer and use it in GitHub Desktop.
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; | |
public static class ContainerExtensions | |
{ | |
public static IEnumerable<(int, T)> Enumerate<T>(this IEnumerable<T> enumerable) | |
{ | |
int index = 0; | |
foreach (T v in enumerable) | |
{ | |
yield return (index, v); | |
index++; | |
} | |
} | |
public static IEnumerable<T> AsEnumerable<T>(params T[] elements) | |
{ | |
return elements.AsEnumerable(); | |
} | |
public static V GetOrAddWith<K, V>(this Dictionary<K, V> dict, K key, Func<V> factory) | |
{ | |
if (!dict.TryGetValue(key, out var value)) | |
{ | |
value = factory(); | |
dict[key] = value; | |
} | |
return value; | |
} | |
public static void AddMulti<K, V>(this Dictionary<K, List<V>> dict, K key, V value) | |
{ | |
if (dict.TryGetValue(key, out var list)) | |
{ | |
list.Add(value); | |
} | |
else | |
{ | |
dict[key] = new List<V>(1) { value }; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment