Question

I have 2 IEnumerable<KeyValuePair<TreeType, int>> collections:

  • _myObject.Trees - contains all the TreeTypes with values of 0.
  • newTrees - can contain any number of TreeTypes with any int value.

Now what I want to do is simple but I've been trying for hours and can't quite get the desired results. I want to insert the newTrees values into the _myobject.Trees collection, so that the _myObject.Trees values won't all be 0.

The closest I've got is below. I know why this doesn't work, but again, I just can't see the solution.

    foreach (var tree in _myObject.Trees)
    {
        foreach (var newTree in newTrees)
        {
            if (tree.Key == newTree.Key)
            {
                _myObject.Trees[tree] =
                    new KeyValuePair<TreeType, int>(newTree.Key, newTree.Value);
                break;
            }
        }
    }

Would really appreciate the help, thanks!

Was it helpful?

Solution

Could you try something like the following:

foreach (var tree in newTrees)
{
     var keyValuePair = _myObject.Trees.Where(s => s.Key == tree.Key).First();
     keyValuePair = new KeyValuePair<Tree, int>(tree.Key, tree.Value);
}

Now you are looping only the newTrees and the Where(...) finds the corresponding element(s) in _myObject.Trees without explicitly looping. Note that the call to First() assumes that any key in newTrees already exists in _myObject.Trees and that it exists only once.

I hope it helps!

OTHER TIPS

Although the Halvard approach provides a good solution for the main problem (+1 for him), it does not state clearly how to store the values in the target positions. Here you have a corrected version of Halvard's code relying on the most typical approach: a Dictionary (one of the multiple posts talking about this):

 Dictionary<TreeType, int> dict = _myObject.Trees.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
 foreach (var tree in newTrees)
 {
     var keyValuePair = _myObject.Trees.Where(s => s.Key == tree.Key);
     if (keyValuePair.Count() > 0)
     {
         dict[keyValuePair.First().Key] = tree.Value; //Value of the given tree associated with the current Key of _myObject.Trees
     }
 }

_myObject.Trees = dict;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top