Files
Cielonos/Assets/Scripts/SLSFramework/General/OrderedDictionaryExtension.cs
SoulliesOfficial ef7b479712 initial
2025-11-25 08:19:33 -05:00

48 lines
1.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections.Generic;
using SoftCircuits.Collections;
using UnityEngine;
namespace SLSFramework.General
{
public static class OrderedDictionaryExtension
{
/// <summary>
/// 根据优先级将元素插入OrderedDictionary中对应的位置保持字典按优先级从高到低排序。
/// </summary>
public static void InsertByPriority<T>(this OrderedDictionary<string, T> dictionary, string key, T value) where T : IPrioritized
{
if (dictionary.ContainsKey(key))
{
Debug.LogWarning($"Key '{key}' already exists in the dictionary. Insertion skipped.");
return;
}
foreach (KeyValuePair<string, T> pair in dictionary)
{
if (value.Priority > pair.Value.Priority)
{
int index = dictionary.IndexOf(pair.Key);
dictionary.Insert(index, key, value);
return;
}
}
dictionary.Add(key, value);
}
/// <summary>
/// 将字典中的元素根据优先级重新排序,保持字典按优先级从高到低排序。
/// </summary>
public static void Sort<T>(this OrderedDictionary<string, T> dictionary) where T : IPrioritized
{
List<KeyValuePair<string, T>> sortedItems = new List<KeyValuePair<string, T>>(dictionary);
sortedItems.Sort((pairA, pairB) => pairA.Value.CompareTo(pairB.Value));
dictionary.Clear();
foreach (KeyValuePair<string, T> item in sortedItems)
{
dictionary.Add(item.Key, item.Value);
}
}
}
}