-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompareDictionaries.cs
89 lines (78 loc) · 2.78 KB
/
CompareDictionaries.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Example dictionaries
var dictionary1 = new ConcurrentDictionary<string, string>
{
["key1"] = "value1",
["key2"] = "value2",
["key3"] = "value3"
};
var dictionary2 = new ConcurrentDictionary<string, string>
{
["key2"] = "value2", // Same value
["key3"] = "updatedValue3", // Updated value
["key4"] = "value4" // New key-value pair
};
// Compare dictionaries
var result = CompareDictionaries(dictionary1, dictionary2);
// Output results
Console.WriteLine("Added:");
foreach (var kvp in result.Added)
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
Console.WriteLine("\nUpdated:");
foreach (var kvp in result.Updated)
Console.WriteLine($"{kvp.Key}: {kvp.OldValue} -> {kvp.NewValue}");
Console.WriteLine("\nDeleted:");
foreach (var kvp in result.Deleted)
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
static ComparisonResult<string, string> CompareDictionaries<TKey, TValue>(
ConcurrentDictionary<TKey, TValue> dict1,
ConcurrentDictionary<TKey, TValue> dict2)
{
var added = new Dictionary<TKey, TValue>();
var updated = new Dictionary<TKey, (TValue OldValue, TValue NewValue)>();
var deleted = new Dictionary<TKey, TValue>();
// Find added and updated keys
foreach (var kvp in dict2)
{
if (!dict1.TryGetValue(kvp.Key, out var oldValue))
{
// Key exists in dict2 but not in dict1 (Added)
added[kvp.Key] = kvp.Value;
}
else if (!EqualityComparer<TValue>.Default.Equals(oldValue, kvp.Value))
{
// Key exists in both but values differ (Updated)
updated[kvp.Key] = (OldValue: oldValue, NewValue: kvp.Value);
}
}
// Find deleted keys
foreach (var kvp in dict1)
{
if (!dict2.ContainsKey(kvp.Key))
{
// Key exists in dict1 but not in dict2 (Deleted)
deleted[kvp.Key] = kvp.Value;
}
}
return new ComparisonResult<TKey, TValue>
{
Added = added,
Updated = updated,
Deleted = deleted
};
}
}
// Result class to store comparison results
class ComparisonResult<TKey, TValue>
{
public Dictionary<TKey, TValue> Added { get; set; } = new();
public Dictionary<TKey, (TValue OldValue, TValue NewValue)> Updated { get; set; } = new();
public Dictionary<TKey, TValue> Deleted { get; set; } = new();
}