Reputation: 545
I need to copy one record from one dictionary to another, only one. I have tried the below, It doesn't copy one but everything due to that its in the loop. And I need to check if the key is not already copied over to the second dictionary that's why I looped over the first dictionary.
foreach (int key in firstDict.Keys)
{
if (!secondDict.ContainsKey(key))
secondDict.Add(key, firstDict[key]);
else {break;}
}
Please help, should you require more info please let me know.
Upvotes: 1
Views: 1489
Reputation: 4744
A tiny bit more efficient than the others answers already posted (saves one dictionary lookup).
foreach(var kvp in firstDict)
{
if(!secondDict.ContainsKey(kvp.Key))
{
secondDict[kvp.Key] = kvp.Value;
break;
}
}
And if you're familiar with linq you may want to avoid the whole foreach ... break
pattern. That pattern is pretty ugly and more importantly confusing: it looks like you want to copy everything when you really want to copy just one. Your question itself is proof of how confusing it is: if you don't get a pattern that should be simple right, that probably means the pattern is not very good. The following will do the work, and it's crystal clear it will only add ONE (at most) entry to the second dictionary.
var missingEntry = firstDict
// cast beacause KeyValuePair is a struct and I want to detect the case where there is no missing entry
.Cast<KeyValuePair<TKey,TValue>?>()
.FirstOrDefault(kvp => !secondDict.ContainsKey(kvp.Key));
// check whether there truely is a missing entry.
if (missingEntry != null)
{
secondDict[missingEntry.Key] = missingEntry.Value;
}
Upvotes: 3
Reputation: 2602
I suppose you have the key of that row in a certain variable that i will call key
. here for example I'll set its value to 3.
int key = 3;
if (!secondDict.ContainsKey(key))
secondDict.Add(key, firstDict[key]);
EDIT: If you want only any single entry that is not present in present in secondDict:
foreach (KeyValuePair<int, MyValueType> kvp in firstDict) //Replace MyValueType with the real value type in firstDict
{
if (!secondDict.ContainsKey(kvp.Key))
{
secondDict.Add(kvp.Key, kvp.Value);
break;
}
}
Upvotes: 1
Reputation: 5214
remove the else clause
foreach (int key in firstDict.Keys)
{
if (!secondDict.ContainsKey(key)) {
secondDict.Add(key, firstDict[key]);
break;
}
}
Upvotes: 1
Reputation: 13979
Try this:
foreach (int key in firstDict.Keys)
{
if (!secondDict.ContainsKey(key))
{
secondDict.Add(key, firstDict[key]);
break;
}
}
Upvotes: 4