-
Notifications
You must be signed in to change notification settings - Fork 5
/
DictionaryExtensions.cs
66 lines (59 loc) · 2.97 KB
/
DictionaryExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DictionaryExtensions.cs" company="Kephas Software SRL">
// Copyright (c) Kephas Software SRL. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
// Extension methods for <see cref="IDictionary{TKey,TValue}" />.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Collections
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// Extension methods for <see cref="IDictionary{TKey,TValue}"/>.
/// </summary>
public static class DictionaryExtensions
{
/// <summary>
/// Tries to get the value for the provided key. If the requested item cannot be found, the default value is returned.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The item's key.</param>
/// <param name="defaultValue">The default value to return if the item could not be found.</param>
/// <returns>The found value, or the default value.</returns>
public static TValue? TryGetValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, [DisallowNull] TKey key, TValue? defaultValue = default)
{
dictionary = dictionary ?? throw new ArgumentNullException(nameof(dictionary));
key = key ?? throw new ArgumentNullException(nameof(key));
return dictionary.TryGetValue(key, out var value) ? value : defaultValue;
}
/// <summary>
/// Tries to get the value for the provided key. If the requested item cannot be found, the default value is returned.
/// </summary>
/// <typeparam name="TDictionary">The dictionary type.</typeparam>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="target">The dictionary where the merge operation occurs.</param>
/// <param name="source">The source dictionary to merge.</param>
/// <returns>The merged dictionary.</returns>
public static TDictionary Merge<TDictionary, TKey, TValue>(this TDictionary target, IDictionary<TKey, TValue>? source)
where TDictionary : class, IDictionary<TKey, TValue>
{
target = target ?? throw new ArgumentNullException(nameof(target));
if (source == null)
{
return target;
}
foreach (var (k, v) in source)
{
target[k] = v;
}
return target;
}
}
}