using System; using System.Collections.Generic; namespace Global.API.Util { public static class CollectionUtils { public static TV ComputeIfAbsent(this Dictionary self, TK key, Func valueCreator) { if (self.ContainsKey(key)) return self[key]; var val = valueCreator(key); self.Add(key, val); return val; } public static void SetOrAdd(this Dictionary self, TK key, Func valueCreator, Func valueIncrement) { if (self.ContainsKey(key)) { var current = self[key]; self.Remove(key); self.Add(key, valueIncrement(current)); return; } var val = valueCreator(key); self.Add(key, val); } public static bool TryGetElementAt(this IReadOnlyList self, int index, out T foundValue) { if (self.Count < index + 1) { foundValue = default; return false; } foundValue = self[index]; return true; } public static T GetElementAtIndexOrElse(this IReadOnlyList self, int index, T defaultValue) { return self.TryGetElementAt(index, out var e) ? e : defaultValue; } } }