Skip to content

Instantly share code, notes, and snippets.

@mattiasflodin
Created May 21, 2018 06:45
Show Gist options
  • Save mattiasflodin/2e1ab731c3c5e0b4d415457fbd8da7b8 to your computer and use it in GitHub Desktop.
Save mattiasflodin/2e1ab731c3c5e0b4d415457fbd8da7b8 to your computer and use it in GitHub Desktop.
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