JD2022-TU1/main/tools/framework/JD.Collections/Extensions/DictionaryExtensions.cs

75 lines
2.3 KiB
C#

using System.Collections.Generic;
using JD.Collections.ObjectModel;
namespace JD.Collections.Extensions
{
/// <summary>
/// Extension methods for IDictionary
/// </summary>
public static class DictionaryExtensions
{
#region AsReadOnly
/// <summary>
/// Returns a read-only wrapper over the given dictionary.
/// </summary>
public static ReadOnlyDictionary<TKey, TValue> AsReadOnly<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
{
return new ReadOnlyDictionary<TKey, TValue>(dictionary);
}
#endregion
#region IsEqualTo
/// <summary>
/// Returns true if the given dictionary is equal (same key/value pairs) to this dictionary.
/// </summary>
public static bool IsEqualTo<TKey, TValue>(this IDictionary<TKey, TValue> a, IDictionary<TKey, TValue> collection)
{
return IsEqualTo(a, collection, EqualityComparer<TValue>.Default);
}
/// <summary>
/// Returns true if the given dictionary is equal (same key/value pairs) to this dictionary.
/// </summary>
public static bool IsEqualTo<TKey, TValue>(this IDictionary<TKey, TValue> a, IDictionary<TKey, TValue> collection, IEqualityComparer<TValue> valueComparer)
{
if (a.Count != collection.Count)
{
return false;
}
foreach (KeyValuePair<TKey, TValue> pair in a)
{
TValue otherValue;
if (!collection.TryGetValue(pair.Key, out otherValue))
{
return false;
}
if (!valueComparer.Equals(pair.Value, otherValue))
{
return false;
}
}
return true;
}
#endregion
#region ValueOrDefault
/// <summary>
/// Returns the value corresponding to the given key in the dictionary or the default value if the key is not in the dictionary.
/// </summary>
public static TValue ValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
{
TValue result;
dictionary.TryGetValue(key, out result);
return result;
}
#endregion
}
}