Files
QuartZ-dump/GlobalTorch/API/Util/CollectionUtils.cs
2024-12-29 21:15:58 +01:00

49 lines
1.4 KiB
C#

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