SoFunction
Updated on 2025-04-06

Dictionary extension base class adds keys and values ​​to dictionary

Add keys and values ​​to the dictionary
Add keys and values ​​are used, but many times, we dare not add them easily, because Dictionary<TKey, TValue> does not allow duplication. When trying to add duplicate keys, the Add method raises an ArgumentException.
Most of the time, we will write the following:

Copy the codeThe code is as follows:

var dict = new Dictionary<int, string>();
// ...
// Case 1: Added if it does not exist
if ((2) == false) (2, "Banana");
// Case 2: Add if there is no existence, replace if there is
if ((3) == false) (3, "Orange");
else dict[3] = "Orange";

In fact, the second case can be written as follows
Copy the codeThe code is as follows:

dict[3] = "Orange";

However, many friends will express doubts about this method and are not sure if this will cause problems.
No matter which way of writing it above, the biggest feeling when using dictionaries is that you are worried and afraid of exceptions, so the code will be written very wordy.
I always use dictionary. After a long time, I am really bored. So I just expanded it and used the following two methods to deal with the above two situations:
Copy the codeThe code is as follows:

/// <summary>
/// Try to add keys and values ​​to the dictionary: if they do not exist, they will only be added; if they do not add or throw away the normal
/// </summary>
public static Dictionary<TKey, TValue> TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
{
    if ((key) == false) (key, value);
    return dict;
}
/// <summary>
/// Add or replace keys and values ​​to dictionary: if not, add; if present, replace
/// </summary>
public static Dictionary<TKey, TValue> AddOrReplace<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
{
    dict[key] = value;
    return dict;
}

The two methods TryAdd and AddOrReplace have strong self-description capabilities, which are worry-free and simple to use:
Copy the codeThe code is as follows:

(2, "Banana");
(3, "Orange");

Or write together like Linq or jQuery:
Copy the codeThe code is as follows:

(1, "A")
    .TryAdd(2, "B")
    .AddOrReplace(3, "C")
    .AddOrReplace(4, "D")
    .TryAdd(5, "E");


Let’s look at another question:

Get the value

Getting values ​​from dictionaries is usually done using the following method

Copy the codeThe code is as follows:

string v = "defaultValue";
// Method 1
if ((3)) v = dict[3];
// Method 2
bool isSuccess = (3, out v);

You must make a judgment before obtaining the index, otherwise a KeyNotFoundException exception will be raised when it does not exist.
I especially hate the second method because using out requires at least two lines of code to declare a variable in advance, which is not concise enough.
Take a look at the GetValue extension:
Copy the codeThe code is as follows:

/// <summary>
/// Get the value associated with the specified key, if not, returns the input default value
/// </summary>
public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default(TValue))
{
    return (key) ? dict[key] : defaultValue;
}

Easy to use:
Copy the codeThe code is as follows:

var v1 = (2);                                                                                                                           �
var v2 = (2, "abc");  //Return "abc" without exist

One line of code can be done.

Add in batches

The List<T> class has an AddRange method, which can directly add another collection to the current collection without the foreach loop:
Copy the codeThe code is as follows:

List<string> roles = new List<string>();
(new[] { "role2", "role2" });
(());

Very convenient, poor Dictionary<TKey, TValue> class does not, but fortunately there is an extension method:
Copy the codeThe code is as follows:

/// <summary>
/// Batch key-value pairs to the dictionary
/// </summary>
/// <param name="replaceExisted">If it already exists, whether to replace</param>
public static Dictionary<TKey, TValue> AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dict, IEnumerable<KeyValuePair<TKey, TValue>> values, bool replaceExisted)
{
    foreach (var item in values)
    {
        if (() == false || replaceExisted)
            dict[] = ;
    }
    return dict;
}

Example of usage:
Copy the codeThe code is as follows:

var dict1 = new Dictionary<int, int>()
    .AddOrReplace(2, 2)
    .AddOrReplace(3, 3);
var dict2 = new Dictionary<int, int>()
    .AddOrReplace(1, 1)
    .AddOrReplace(2, 1)
    .AddRange(dict1, false);