25 lines
715 B
C#
25 lines
715 B
C#
namespace AdventOfCode;
|
|
|
|
public static class EnumerableExtensions
|
|
{
|
|
public static IEnumerable<TSource> Flatten<TSource>(this TSource root, Func<TSource, IEnumerable<TSource>> flattener)
|
|
{
|
|
var toVisit = new Stack<TSource>();
|
|
toVisit.Push(root);
|
|
|
|
while (toVisit.TryPop(out var node))
|
|
{
|
|
yield return node;
|
|
|
|
foreach (var child in flattener(node))
|
|
{
|
|
toVisit.Push(child);
|
|
}
|
|
}
|
|
}
|
|
|
|
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
|
|
{
|
|
return dictionary.TryGetValue(key, out var value) ? value : defaultValue;
|
|
}
|
|
} |