namespace adas_core.Domain.Utils; /// /// Provides static extension methods to augment the functionality of dictionary types. /// public static class DictionaryEx { /// /// Retrieves the value associated with the specified key from the dictionary, or returns the provided default value if the key is not found. /// /// The dictionary to search for the key. /// The key whose associated value should be returned. /// The value to return when the key is not present in the dictionary. Defaults to the default value of . /// The value associated with the key if found; otherwise, . public static TV? GetValue(this IDictionary dict, TK key, TV? defaultValue = default) { return dict.TryGetValue(key, out var value) ? value : defaultValue; } /// /// Converts a dictionary into a formatted string by joining each key-value pair with a key separator and concatenating all pairs with an item separator. /// /// The source dictionary whose entries will be converted to a string. /// The separator placed between each formatted key-value pair in the resulting string. /// The separator placed between a key and its corresponding value within each pair. /// A single string containing all dictionary entries formatted and joined using the specified separators. public static string ToListString(this IDictionary dict, string itemSeparator = ", ", string keySeparator = ": ") { var s = dict.Keys.Select(key => key + keySeparator + dict[key]).ToList(); return string.Join(itemSeparator, s); } /// /// Attempts to retrieve the value associated with the specified key from the dictionary, returning null if the key is not found. /// /// The dictionary to search for the key. /// The key whose associated value should be retrieved. /// The value associated with the key, or null if the key was not found in the dictionary. public static TValue? TryGetAndReturn(this IDictionary dictionary, TKey key) where TKey : notnull where TValue : class { if (!dictionary.TryGetValue(key, out var retValue)) retValue = null; return retValue; } }