using System.Text;
namespace System.Collections.Generic
{
[UnityEngine.Scripting.Preserve]
public static class CollectionExtensions
{
#region DictionaryExtensions
///
/// 将k和v进行合并
///
///
///
///
///
///
///
[UnityEngine.Scripting.Preserve]
public static void Merge(this Dictionary self, TKey k, TValue v, Func func)
{
self[k] = self.TryGetValue(k, out var value) ? func(value, v) : v;
}
///
/// 根据key获取value值,当不存在时通过valueGetter生成value,放入Dictionary并返回value
///
[UnityEngine.Scripting.Preserve]
public static TValue GetOrAdd(this Dictionary self, TKey key, Func valueGetter)
{
if (!self.TryGetValue(key, out var value))
{
value = valueGetter(key);
self[key] = value;
}
return value;
}
///
/// 根据key获取value值,当不存在时通过默认构造函数生成value,放入Dictionary并返回value
///
[UnityEngine.Scripting.Preserve]
public static TValue GetOrAdd(this Dictionary self, TKey key) where TValue : new()
{
return GetOrAdd(self, key, k => new TValue());
}
///
/// 根据条件移除
///
[UnityEngine.Scripting.Preserve]
public static int RemoveIf(this Dictionary self, Func predict)
{
int count = 0;
var remove = new HashSet();
foreach (var kv in self)
{
if (predict(kv.Key, kv.Value))
{
remove.Add(kv.Key);
count++;
}
}
foreach (var key in remove)
{
self.Remove(key);
}
return count;
}
#endregion
#region ICollectionExtensions
[UnityEngine.Scripting.Preserve]
public static bool IsNullOrEmpty(this ICollection self)
{
return self == null || self.Count <= 0;
}
#endregion
#region List
///
/// 打乱
///
[UnityEngine.Scripting.Preserve]
public static void Shuffer(this List list)
{
int n = list.Count;
var r = ThreadLocalRandom.Current;
for (int i = 0; i < n; i++)
{
int rand = r.Next(i, n);
(list[i], list[rand]) = (list[rand], list[i]);
}
}
[UnityEngine.Scripting.Preserve]
public static void RemoveIf(this List list, Predicate condition)
{
var idx = list.FindIndex(condition);
while (idx >= 0)
{
list.RemoveAt(idx);
idx = list.FindIndex(condition);
}
}
private static readonly StringBuilder ListToStringBuilder = new StringBuilder();
///
/// 将列表转换为以指定字符串分割的字符串
///
///
/// 默认为逗号
///
///
[UnityEngine.Scripting.Preserve]
public static string ListToString(this List list, string separator = ",")
{
ListToStringBuilder.Clear();
foreach (T t in list)
{
ListToStringBuilder.Append(t);
ListToStringBuilder.Append(separator);
}
return ListToStringBuilder.ToString();
}
#endregion
[UnityEngine.Scripting.Preserve]
public static void AddRange(this HashSet c, IEnumerable e)
{
foreach (var item in e)
{
c.Add(item);
}
}
}
}