c# - Given two dictionaries, how do you overwrite matching items in one with items in the other, leaving the remaining items untouched -
here starting code:
dictionary<string,object> dest=...; idictionary<string,object> source=...; // overwrite in dest of items appear in source new values // in source. new items in source not appear in dest should added. // existing items in dest, not in source should retain current // values. ... i can foreach loop goes through of items in source, there shorthand way in c# 4.0 (perhaps linq)?
thanks
the foreach pretty small. why complicate things?
foreach(var src in source) { dest[src.key] = src.value; } if you're going repeat often, write extension method:
public static void mergewith<tkey, tvalue>(this dictionary<tkey,tvalue> dest, idictionary<tkey, tvalue> source) { foreach(var src in source) { dest[src.key] = src.value; } } //usage: dest.mergewith(source); as doing "with linq", query part means linq method should have no side effects. having side effects confusing of expect no side effects it.
Comments
Post a Comment