ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Merge

Merges two dictionaries

Source

/// <summary>
/// Merges the current data to a new data
/// </summary>
/// <param name="data"></param>
public static void Merge<TKey, TValue>(this IDictionary<TKey, TValue> to, IDictionary<TKey, TValue> data)
{
    foreach (var item in data)
    {
        if (to.ContainsKey(item.Key) == false)
        {
            to.Add(item.Key, item.Value);
        }
    }
}

Example

public void Test_MergeDictionary()
{
    Dictionary<string, string> dic1 = new Dictionary<string, string>();
    Dictionary<string, string> dic2 = new Dictionary<string, string>();

    dic1.Add("Key01", "Value1");
    dic1.Add("Key04", "Value4");
    dic1.Add("Key03", "Value3");
    dic1.Add("Key02", "Value2");

    dic2.Add("Key01", "Value1");
    dic2.Add("Key04", "Value4");
    dic2.Add("Key02", "Value2");
    dic2.Add("Key03", "Value3");
    dic2.Add("Key05", "Value5");

    dic1.Merge(dic2);
}

Author: mInternauta

Submitted on: 1 mei 2016

Language: C#

Type: Dictionary

Views: 6073