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

ContainsSameKeys<>

Checks if the two dictionaries have the same keys

Source

/// <summary>
/// Check if the two dictionaries have the same keys
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="from">Parent Dictionary</param>
/// <param name="to">Child Dictionary</param>
/// <returns></returns>
public static bool ContainsSameKeys<TKey, TValue>(this IDictionary<TKey, TValue> from, IDictionary<TKey, TValue> to)
{
    var search = to
       .Keys
       .Where(p => from.Keys.Contains(p));
    return (search.Count() == from.Count);
}

Example

[TestMethod]
public void Test_ContainsSameKeys()
{
    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");

    Assert.IsTrue(dic1.ContainsSameKeys(dic2));
}

Author: mInternauta

Submitted on: 1 mei 2016

Language: C#

Type: IDicitionary

Views: 4749