using System.Collections.Immutable; using System.Reflection; using Connected.Annotations; namespace Connected.Collections; public static class CollectionExtensions { public static ImmutableArray ToImmutableArray(this IEnumerable items, bool performLock) { if (!performLock) return items.ToImmutableArray(); lock (items) return items.ToImmutableArray(); } public static ImmutableList ToImmutableList(this IEnumerable items, bool performLock) { if (!performLock) return items.ToImmutableList(); lock (items) return items.ToImmutableList(); } public static void SortByOrdinal(this List items) { items.Sort((left, right) => { var leftOrdinal = left is Type lt ? lt.GetCustomAttribute() : left?.GetType().GetCustomAttribute(); var rightOrdinal = right is Type rt ? rt.GetCustomAttribute() : right?.GetType().GetCustomAttribute(); if (leftOrdinal is null && rightOrdinal is null) return 0; if (leftOrdinal is not null && rightOrdinal is null) return -1; if (leftOrdinal is null && rightOrdinal is not null) return 1; if (leftOrdinal?.Value == rightOrdinal?.Value) return 0; else if (leftOrdinal?.Value < rightOrdinal?.Value) return 1; else return -1; }); } public static void SortByPriority(this List items) { items.Sort((left, right) => { var leftPriority = left is Type lt ? lt.GetCustomAttribute() : left?.GetType().GetCustomAttribute(); var rightPriority = right is Type rt ? rt.GetCustomAttribute() : right?.GetType().GetCustomAttribute(); if (leftPriority is null && rightPriority is null) return 0; if (leftPriority is not null && rightPriority is null) return -1; if (leftPriority is null && rightPriority is not null) return 1; if (leftPriority?.Value == rightPriority?.Value) return 0; else if (leftPriority?.Value > rightPriority?.Value) return -1; else return 1; }); } }