49 lines
1.4 KiB
C#
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;
|
|
}
|
|
}
|
|
} |