// ========================================================================== // CollectionExtensions.cs // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex Group // All rights reserved. // ========================================================================== using System; using System.Collections.Generic; using System.Linq; // ReSharper disable InvertIf // ReSharper disable LoopCanBeConvertedToQuery namespace Squidex.Infrastructure { public static class CollectionExtensions { public static int SequentialHashCode(this IEnumerable collection) { return collection.SequentialHashCode(EqualityComparer.Default); } public static int SequentialHashCode(this IEnumerable collection, IEqualityComparer comparer) { var hashCode = 17; foreach (var item in collection) { if (item != null) { hashCode = hashCode * 23 + item.GetHashCode(); } } return hashCode; } public static int OrderedHashCode(this IEnumerable collection) { return collection.OrderedHashCode(EqualityComparer.Default); } public static int OrderedHashCode(this IEnumerable collection, IEqualityComparer comparer) { var hashCodes = collection.Where(x => x != null).Select(x => x.GetHashCode()).OrderBy(x => x).ToArray(); var hashCode = 17; foreach (var code in hashCodes) { hashCode = hashCode * 23 + code; } return hashCode; } public static bool EqualsDictionary(this IReadOnlyDictionary dictionary, IDictionary other) { return Equals(dictionary, other) || (other != null && dictionary.Count == other.Count && !dictionary.Except(other).Any()); } public static TValue GetOrDefault(this IReadOnlyDictionary dictionary, TKey key) { return dictionary.GetOrCreate(key, _ => default(TValue)); } public static TValue GetOrAddDefault(this IDictionary dictionary, TKey key) { return dictionary.GetOrAdd(key, _ => default(TValue)); } public static TValue GetOrNew(this IReadOnlyDictionary dictionary, TKey key) where TValue : class, new() { return dictionary.GetOrCreate(key, _ => new TValue()); } public static TValue GetOrAddNew(this IDictionary dictionary, TKey key) where TValue : class, new() { return dictionary.GetOrAdd(key, _ => new TValue()); } public static TValue GetOrCreate(this IReadOnlyDictionary dictionary, TKey key, Func creator) { TValue result; if (!dictionary.TryGetValue(key, out result)) { result = creator(key); } return result; } public static TValue GetOrAdd(this IDictionary dictionary, TKey key, Func creator) { TValue result; if (!dictionary.TryGetValue(key, out result)) { result = creator(key); dictionary.Add(key, result); } return result; } } }