After some research, found we can use conditional statement in Liunq ForEach like so to get new or updated dictionary items,
Add or Update Dictionary Union
kvs2.Keys.ToList().ForEach(x =>{
if (kvs.ContainsKey(x))
{
kvs[x] = kvs2[x];
}
else
{
kvs.Add(x, kvs2[x]);
}
});
C# Case Insensitive Dictionary, Merging dictionaries
Dictionary<string, string> kvs = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);kvs.Add("UserID", "Asdasd");
kvs.Add("Password", "Asdasd");
Dictionary<string, string> kvs2 = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
kvs2.Add("userid", "NewUser");
kvs2.Add("userid2", "Asdasd");
kvs2.Add("PASSWORD", "NePWD");
kvs2.Add("PASSWORD2", "Asdasd");
//var newDict = kvs.Union(kvs2).GroupBy(d => d.Key).ToDictionary(d => d.Key, d => d.First().Value);
//var newDict = kvs.Union(kvs2).GroupBy(d => d.Key).ToDictionary(d => d.Key, d => (kvs2.ContainsKey(d.Key) ? kvs2[d.key] : d.First().Value));
var newDict = kvs.Union(kvs2).GroupBy(d => d.Key).ToDictionary(d => d.Key, d => (kvs2.ContainsKey(d.Key) ? kvs2[d.Key] : d.First().Value));
newDict.Keys.ToList().ForEach(x => Debug.WriteLine(string.Format("Key={0}-> Value={1}", x, newDict[x])));
var newDict2 = kvs.Concat(kvs2.Where(x => !kvs.Keys.Contains(x.Key))).ToDictionary(d => d.Key, d => d.Value);
newDict2.Keys.ToList().ForEach(x => Debug.WriteLine(string.Format("Key={0}-> Value={1}", x, newDict[x])));
No comments:
Post a Comment